Pages

Saturday, June 29, 2013

Recursive solution of determining whether a string is plaindrome or not in C++

/*
QUESTION:
Write a recursive solution of determining whether a string is palindrome or not. Note: a palindrome string is that which can be read the same forward or backward e.g; racecar, mom etc
*/
// CODE:
#include <iostream>
using namespace std;

bool palindrome(char[], int size);
//MAIN STARTS
int main()
{
 cout << "Enter a stringing: ";

 char string[50];

 cin.getline(string,50,'\n');

 cout << "The entered stringing " << ( (palindrome(string,strlen(string)+1))? "is":"is not" ) << " a Palindrome string." << endl;
 return 0;
}

//MAIN ENDS
bool palindrome(char string[], int size)
{
 if (string[0] != string[size-2]) //check for first and last element
  return false;
 if (strlen(string) <= 1)
  return true;
 else
  return palindrome(string+1,size-2);
}

No comments:

Post a Comment