Palindrome

Palindrome string is a string which is same as if all characters are reversed. Simple way to check is to duplicate the string and make a reversed string. Then compare this original string with the reversed string. We would require to use strdup, strrev and strcmp/strcmpi for this.

Palindrome check with string lib- source code

#include <stdio.h>
#include<string.h>
#include<malloc.h>
int main(int argc, char* argv[])
{
  char buffer[100];
  char * rbuffer;
  printf("Enter a string :");
  scanf("%[^\n]", buffer);
10    rbuffer = strdup(buffer);
11    strrev(rbuffer);
12    if (strcmpi(rbuffer, buffer) != 0) {
13      printf ("%s is not palindrome.\n", buffer);
14    } else {
15      printf ("%s is palindrome.\n", buffer);
16    }
17    free(rbuffer);
18    return 0;
19  }
20 

Palindrome check without string function

Palindrome string check is easy with string library functions. However this uses string library functions and uses additional memory allocation. We can write a simple logic to avoid using these functions. We need to check the length of the string and then need to compare character pairs like 0 and(len-1), 1 and (len -2). We can iterate till mid point. If character pairs are same then we can declare the string as palindrome else we can immediately terminate the loop and say it is not palindrome.

Palindrome check- source code

#include <stdio.h>
#include<ctype.h>
int main(int argc, char* argv[])
{
  int len, i;
  char buffer[100];
  printf("Enter a string :");
  scanf("%[^\n]", buffer);
  i = 0;
10    len = 0;
11    while(buffer[i] != NULL){
12      len++;
13      i++;
14    }
15    for(= 0; i < len/2; i++) {
16      if(tolower(buffer[i]) != tolower(buffer[len - 1 - i])) {
17        printf ("%s is not palindrome.\n", buffer);
18        return -1;
19      }
20    }
21    printf ("%s is palindrome.\n", buffer);
22    return 0;
23  }
24 

Palindrome check - output

Enter a string :Hello World!
Hello World! is not palindrome.

Enter a string :Madam
Madam is palindrome.

Enter a string :asdfghjkl lkjhgfdsa
asdfghjkl lkjhgfdsa is palindrome.

You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.

 Vote 0

Similar topics related to this section

Circular buffer, char array and char pointers, const char *,char * const, const char * const, alpha numeric, palindrome, convert case, string to int, int to string,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan