C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Check palindrome string

C Program: Check Palindrome String (Without strrev())

Method 1: Using gets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

    int i, length = 0, flag = 0;

 

    // Input string

    printf("Enter a string: ");

    gets(str); // unsafe, use fgets() in practice

 

    // Find length of the string

    for (i = 0; str[i] != '\0'; i++) {

        length++;

    }

 

    // Check palindrome

    for (i = 0; i < length / 2; i++) {

        if (str[i] != str[length - i - 1]) {

            flag = 1;

            break;

        }

    }

 

    // Display result

    if (flag == 0)

        printf("The string is a palindrome.\n");

    else

        printf("The string is not a palindrome.\n");

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: madam
The string is a palindrome.


OUTPUT 2 :
Enter a string: hello
The string is not a palindrome.

Explanation

  1. The program accepts a string and calculates its length
  2. It then compares characters from the start and end of the string.
  3. If any pair doesn’t match, it sets flag = 1 and breaks the loop.
  4. If all pairs match, the string is a palindrome.

 

C Program: Check Palindrome String (Without strrev())

Method 2: Using fgets() function

C

#include <stdio.h>

 

int main() {

    char str[100];

    int i, length = 0, flag = 0;

 

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    // Remove newline character if present

    for (i = 0; str[i] != '\0'; i++) {

        if (str[i] == '\n') {

            str[i] = '\0';

            break;

        }

        length++;

    }

 

    // Check palindrome

    for (i = 0; i < length / 2; i++) {

        if (str[i] != str[length - i - 1]) {

            flag = 1;

            break;

        }

    }

 

    if (flag == 0)

        printf("The string is a palindrome.\n");

    else

        printf("The string is not a palindrome.\n");

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter a string: madam
The string is a palindrome.


OUTPUT 2 :
Enter a string: hello
The string is not a palindrome.

Explanation

  1. The program accepts a string and calculates its length
  2. It then compares characters from the start and end of the string.
  3. If any pair doesn’t match, it sets flag = 1 and breaks the loop.
  4. If all pairs match, the string is a palindrome.