This blog is under construction

Sunday, 21 July 2013

C program to check whether the given string is palindrome or not using recursion

Write a C program to check whether the given string is palindrome or not using recursion.


  #include <stdio.h>
  #include <string.h>

  /* checks whether the given string is palindrome or not */
  int isPalindrome(char *str, char *rev) {
        int ret;

        /* parsed whole string.. so palindrome */
        if (*str == '\0') {
                return 1;
        } else if (*str != *rev) {
                /* any character mismatch - not a palindrome */
                return 0;
        }

        /* recursive call */
        ret = isPalindrome(str + 1, rev - 1);
        return ret;
  }

  int main() {
        char str[256], ret;

        /* get the input string from the user */
        printf("Enter your input string:");
        fgets(str, 256, stdin);
        str[strlen(str) - 1] = '\0';

        /* checks whether i/p string is palindrome or not */
        ret = isPalindrome(str, str + (strlen(str) - 1));

        /* printing the result */
        if (ret) {
                printf("%s is a palindrome\n", str);
        } else {
                printf("%s is not a palindrome\n", str);
        }
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input string: madam
  madam is a palindrome


No comments:

Post a Comment