Home / Programs / C Program to Check whether the Given String is a Palindrome
🚀 Programming Example

C Program to Check whether the Given String is a Palindrome

👁 1,218 Views
💻 Practical Program
📘 Step Learning
Palindrome is a string, which when read in both forward and backward way is same.

💻 Program Code

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

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

                        

🖥 Program Output

<b>Output 1</b>
Enter a string:roor
roor is a palindrome
Press any key to continue . . .

<b>Output 2</b>
Enter a string:rum
rum is not a palindrome
Press any key to continue . . .
                            

📘 Explanation

To check if a string is a palindrome or not, a 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. 0th character in the char array, string1 is same as 4th character in the same string.
  2. 1st character is same as 3rd character.
  3. 2nd character is same as 2nd character.
  4. . . . .
  5. ith character is same as 'length-i-1'th character.
  6. If any one of the above condition fails, flag is set to true(1), which implies that the string is not a palindrome.
  7. By default, the value of flag is false(0). Hence, if all the conditions are satisfied, the string is a palindrome.
📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.