Need a project done?

C++ Programming Developer

Search This Blog

Whether a given string (char array) is Palindrome or not in C++


/*
Write a function to check whether a given string (char array) is
Palindrome or not. Your program should take only one parameter char array and
should return 1 if string is Palindrome otherwise it must return 0.
Note: A string is a Palindrome if it is same whether read from left to right or from
right to left. For example aba is a Palindrome.
*/

#include <iostream>
using namespace std;

bool Palindrome(char []);

int main()
{
cout << "Write something, I'll tell whether it's Palindorme or Not:\n\n";
char s[50];
cin.getline(s,50,'\n');

cout << "\nYou "<< ((Palindrome(s) == 1)? "":"did not ")<<  "entered a Palindrome String." << endl;

return 0;
}

bool Palindrome(char s[])
{
//we'll locate Null character in the string.
for (int i = 0; s[i] != '\0'; i++);
//Now we've Null character at s[i].
//therefore we can start comparing to know whether this string is palindrome or not.
//int Null_Character = i.
i--;// Now s[i] is the last character of string.
for (int j = 0; j<i; j++,i--)
{
if (s[j] != s[i])
{
return 0;
}
}
return 1;
}

2 comments:

  1. The code has an error , the "i--;" is the cause of the error but I don't know what is meant to be there

    ReplyDelete

"Don't let anyone ever make you feel like you don't deserve what you want."