Recursive function to check if a string is palindrome in C++

C++Server Side ProgrammingProgramming

We are given a string Str as input. The goal is to find if the input string is a palindrome word or not using a recursive function. Palindrome strings are those strings that when read from front or end form the same word. The strings of length 0 are considered as palindromes. Reversing the palindromes character wise forms, the same string as the original.

Examples of palindromes are:- madam, abcba, malayalam etc

Examples

Input − Str = “malayalam”

Output − Input string is palindrome.

Explanation 

Str[ 0 to 8 ] = malayalam

Reverse Str [ 8 to 0 ] = malayalam

Both strings are same.

Input − Str = “tutorial”

Output − Input string is not a palindrome.

Explanation

Str[ 0 to 7 ] = tutorial

Reverse Str [ 7 to 0 ] = lairotut

Both strings are different

Approach used in the below program is as follows

In this approach we will check if the string contains a single character, if true then it is palindrome. If not, then recursively traverse the whole string for remaining characters and break the recursion if corresponding characters are different.

  • Take the input string Str[] and calculate its length.

  • If length is 0 then set result=1.

  • Else set result=checkPalindrome(Str, 0, length - 1) where 0 is first index and lenght - 1 is last index

  • Function checkPalindrome(char str[], int first, int last) returns 0 if any character does not match with its corresponding character in the string.

  • If indexes first and last are the same then string has one character, then return 1.

  • If not then check the remaining characters except end characters by first++, last-- and recursive call checkPalindrome(str, first, last).

  • At the end of all recursions we will get a result.

  • If it is 1 then the input string is palindrome.

  • Else input string is not a palindrome.

  • Print result in main.

Example

#include <bits/stdc++.h>
using namespace std;
int checkPalindrome(char str[], int first, int last){
   if (first < last + 1){
      first++;
      last--;
      return checkPalindrome(str, first, last);
   }

   if (first == last){
      return 1;
   }
   if (str[first] != str[last]){
      return 0;
   }
   return 1;
}
// Driver Code
int main(){
   char Str[] = "madam";
   int result;
   int length = strlen(Str);
   if (length == 0){
      result=1;
   }

   else{
      result=checkPalindrome(Str, 0, length - 1);
   }
   if (result==1){
      cout << "Input string is palindrome.";
   }
   else{
      cout << "Input string is not a palindrome.";
   }
   return 0;
}

Output

If we run the above code it will generate the following Output

Input string is palindrome.
raja
Published on 02-Nov-2021 08:05:39
Advertisements