Need a project done?

C++ Programming Developer

Search This Blog

Palindrome Recursion C++

Write a recursive function of determining whether a string is palindrome or not.
Note: A palindrome is a string that can be read the same both forward and backwards such as racecar, mom etc.

Solution:
Explanation: Click here to understand each step.

#include <iostream>
using namespace std;

bool palindrome(char[], int size);

bool main()
{
cout << "Enter a string: ";
char str[20];

cin.getline(str,20,'\n');
cout << "The entered string " << ( (palindrome(str,strlen(str)+1))? "is":"is not" ) << " a Palindrome string." << endl;
//If you didn't understand ?: click here.
return 0;
}

bool palindrome(char str[], int size)
{
if (str[0] != str[size-2]) //if first element is not equal to last element.
return false;
else if (strlen(str) <= 1)
return true;
else
return palindrome(str+1,size-2);
}


2 comments:

  1. There are some problems in it,
    1: the last element of string will be (size-1) instead of (size-2);

    2: this function doesnot works if I entered the input string as "razar" which is due to the wrong Logic;

    3: Better to avoid built in functions in recursion technique;

    4: One of the example is below
    bool palidrome_check ( char strn [] , int size , int begin = 0 )
    {
    if ( begin == size )//begin is the starting index
    return true;
    else
    {
    if( begin+1 == size)
    {
    if(strn[begin]==strn[size])
    {
    return true;
    }
    else return false;
    }
    else
    {
    if( strn [begin] == strn[size] )
    {
    if ( palidrome_check(strn,size-1,begin+1 ) )
    {
    return true;
    }
    else
    {
    return false;
    }
    }
    else
    {
    return false;
    }
    }
    }
    }

    ReplyDelete
    Replies
    1. 1. I've passed strlen(str)+1 in palindrome(str,strlen(str)+1), which means that the size is one more than the value given by strlen, this was because I took into account the '\0' character. Now the last element will be str[size-2], because array starts from 0 and null character is excluded.
      So what I've done is absolutely correct.

      2. It's working perfectly for "razar". I've rechecked.

      3. Thanks, I'll take care. Any ways what will u use in order to get the size of array in main other than strlen?

      4. There are many ways to reach to ur destination. Thanks!

      Delete

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