C Programming Examples Tutorial Index

C Array Programs

A palindrome is a string, which is the same when read in both forward and backward ways.



Example:

radar, madam, pop, lol, etc.

Palindrome String Check Program in C

Example:

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

int main(){
    char string1[20];
    int i, length;
    int flag = 0;
    
    printf("Enter a string:");
    scanf("%s", string1);
    
    length = strlen(string1);
    
    for(i=0;i < length ;i++){
        if(string1[i] != string1[length-i-1]){
            flag = 1;
            break;
           }
        }
    
    if (flag) {
        printf("%s is not a palindrome", string1);
    }    
    else {
        printf("%s is a palindrome", string1);
    }
    return 0;
}

Program Output:

palindrome-string

Explanation:

To check if a string is a palindrome or not, the string needs to be compared with the reverse of itself.

Consider a palindrome string: radar,

---------------------------
index: 0 1 2 3 4

value: r a d a r
---------------------------

Palindrome String

To compare it with the reverse of itself, the following logic is used:

  1. The 0th character in the char array, string1, is the same as the 4th character in the same string.
  2. 1st character is the same as 3rd character.
  3. 2nd character is the same as 2nd character.
  4. . . . .
  5. ith character is the same as the 'length-i-1'th character.
  6. If any of the above conditions fails, the flag is set to true(1), implying that the string is not a palindrome.
  7. By default, the value of the flag is false(0). Hence, the string is a palindrome if all the conditions are satisfied.


Found This Useful? Share This Page!