C program to check if a string is palindrome or not

C program to check if a string is palindrome or not :

In this tutorial, we will learn how to check if a string is palindrome or not using ‘c programming language’. A palindrome string is a string that is same if we reverse it. For example string abccba is palindrome. Because if we reverse it, it will be same. Let’s take a look into the program first :

C program :

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

int main()
{
	//1
	char *str;
	int i;
	int size;
	int mid;

	//2
	str = malloc(sizeof(char) * 255);

	//3
	printf("Enter a string : ");
	scanf("%[^\n]s",str);

	//4
	size = strlen(str);

	//5
	for(i = 0; i < size/2 ;i++){
	//6
	 	if(tolower(str[i]) != tolower(str[size - 1 -i])){
	 		printf("Not a palindrome string.\n");
	 		break;
	 	}
	}

	//7
	if(i==size/2){
	 	printf("Entered string is palindrome.\n");
	}
}

Explanation :

The commented numbers in the above program denotes the step-number below :

In this example, we are using stdlib.h , string.h and ctype.h. If you want to know exactly where any one of these is used, remove the line and try to compile : it will show you the error on that line :)

  1. Create one character pointer variable ‘str’ to store the string. One variable ‘i’ to use in the loop , one variable to store the size of the string size , one variable to store middle size of the string ‘mid’.
  2. Now, to store a string in the ‘str’ variable, we need to allocate memory . Use malloc to allocate memory for 255 characters.
  3. Get the input from the user and store the string in ‘str’ variable.
  4. Get the length of the input string using strlen method and store it in size variable.
  5. Now, using one for loop, we will check each character of the string till mid point.
  6. Compare the character of the start position with the end character of the equivalent position. For example, for the string ‘abccba’ , first check first a with the last a, then the second position b with last second position b etc. If two characters are not equal, print that it is not palindrome and exit from the loop using break. Note that we are comparing both characters by converting them into lower case first.
  7. After the loop is completed, check if value of i is size/2 , i.e. the loop complets of not. If the loop is completed, means no equal characters are found. i.e. it is a palindrome string. Print it.

Example :

Enter a string : abccba
Entered string is palindrome.

Enter a string : apple
Not a palindrome string.

Enter a string : racecar
Entered string is palindrome.