This blog is under construction

Monday 24 June 2013

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

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


  #include <stdio.h>
  #include <string.h>
  int main() {
        char str[100], rev[100];
        int len, i = 0, flag = 0;

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

        /* find the lenght of the given string */
        len = strlen(str) - 1;

        /* reverse of the give string */
        while (len >= 0) {
                rev[i++] = str[len--];
        }
        rev[i] = '\0';
        len = 0;

        /* check whether the input string and reverse are same */
        while (len < strlen(str)) {
                if (str[len] != rev[len]) {
                        printf("%s is not a palindrome\n", str);
                        flag = 1;
                        break;
                }
                len++;
        }

        /* if flag is not set - then the input string is palindrome */
        if (!flag)
                printf("%s is a palindrome\n", str);
        return 0;
  }



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



No comments:

Post a Comment