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);
  rbuffer = strdup(buffer);
  strrev(rbuffer);
  if (strcmpi(rbuffer, buffer) != 0) {
    printf ("%s is not palindrome.\n", buffer);
  } else {
    printf ("%s is palindrome.\n", buffer);
  }
  free(rbuffer);
  return 0;
}

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;
  len = 0;
  while(buffer[i] != NULL){
    len++;
    i++;
  }
  for(= 0; i < len/2; i++) {
    if(tolower(buffer[i]) != tolower(buffer[len - 1 - i])) {
      printf ("%s is not palindrome.\n", buffer);
      return -1;
    }
  }
  printf ("%s is palindrome.\n", buffer);
  return 0;
}

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.

About our authors: Team EQA

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

#