Program to check whether the string is palindrome or not |C Program|

Introduction

     Palindrome detection is a classic problem in computer science and programming. In this blog post, we'll explore a C program that checks whether a given string is a palindrome or not. Palindromes, which read the same backward as forward, provide a great opportunity to understand string manipulation and looping in C.  

Code

    
     
    #include<stdio.h>
    #include<conio.h>
    #include<string.h>
    void main() {
        int i, length;
        char str[20];
        int flag = 0;
        printf("Enter a string: ");
        scanf("%s", &str);
        length = strlen(str);

        for (i = 0; i &lt length; i++) {
            if (str[i] != str[length - i - 1]) {
                flag = 1;
                break;
            }
        }

        if (flag) {
            printf("%s is not a palindrome", str);
        } else {
            printf("%s is a palindrome", str);
        }
        getch();
    }
       
     


Output


    enter a string:malayalam
    malayalam is a palindrome
       




Explanation

1. Header Files:
The program includes the standard input/output header <stdio.h>, the console I/O header <conio.h>, and the string manipulation header <string.h>.
2. Main Function:
The main function initiates the program.
Users are prompted to enter a string, and the input is stored in the character array str.
The length of the entered string is determined using strlen.
3. Palindrome Checking:
A for loop iterates through the characters of the string.
The loop compares characters from the beginning and end of the string, checking if they are equal.
If a mismatch is found, the flag is set to 1, and the loop breaks.
4. Result Display:
Based on the value of the flag, the program prints whether the entered string is a palindrome or not.
5. User Interaction:
Users receive clear feedback about whether the entered string is a palindrome or not. 


Conclusion

     This C program provides a simple yet effective solution for checking whether a given string is a palindrome. While the code is straightforward, it highlights the importance of string manipulation and loop structures in programming. Experiment with different input strings, try understanding the flow of the program, and consider optimizations or alternative approaches. Understanding how to handle strings and implement logical checks is crucial for tackling more complex programming challenges. Palindromes, with their symmetric properties, offer an excellent opportunity to hone these skills. Happy coding!

Post a Comment

0 Comments