C program to check if the string is a palindrome

C program to check if the string is a palindrome

This C program is to check if the string is a palindrome or not.Palindrome strings are which when written in reverse also produce the same string.For example, dad is a palindromic string as when written in reverse also produces string dad.

Logic

We keep comparing the first character with the last, the second with second last and so on.If at any instant both characters do not match we for sure know that it is not a palindrome.

Dry Run of the Program

Take input string ‘str’.Let us take str=dad

flag is initialized to 0 i.e. flag=0

n=strlen(str); hence n=3

1st iteration for(i=0;i<n;i++) i.e. for(i=0;0<3;i++)

if(str[i]!=str[n-i-1]) i.e. if(str[0]!=str[3-0-1]) i.e. if(str[0]!=str[2]) i.e. if(d!=d) which is false as d=d

2nd iteration for(i=1;i<n;i++) i.e. for(i=1;1<3;i++)

if(str[i]!=str[n-i-1]) i.e. if(str[1]!=str[3-1-1]) i.e. if(str[1]!=str[1]) i.e. if(a!=a) which is false as a=a

3rd iteration for(i=2;2<n;i++) i.e. for(i=2;2<3;i++)

if(str[i]!=str[n-i-1]) i.e. if(str[2]!=str[3-2-1]) i.e. if(str[2]!=str[0]) i.e. if(d!=d) which is false as d=d

For loop ends here as now i(3) is not less than n(3).

if(flag==0) i.e. if(0==0) true

We print that the given string “dad” is a palindrome.

Program

#include <stdio.h>
#include<string.h>
void main()
{
    int n,i,flag=0;
    char str[101];
    
    printf("Enter a string\n");
    gets(str);
    
    n=strlen(str);
    for(i=0;i<n;i++)
    {
        if(str[i]!=str[n-i-1])
        {
            flag=1;
            break;
        }
    }
        printf("Is the string a palindrome?\n");
        if(flag==0)
        {
            printf("YES");
        }
        else
        {
            printf("NO");
        }   
}

Output

Share Me!