Skip to main content

Palindrome string using function

Short answer

Define a function that compares characters from both ends moving inward. If any pair differs, return 0 (not palindrome); if all match, return1 (palindrome).

Write a program in C to check whether a given string is palindrome or not using user defined function.

A palindrome reads the same from both ends (madam, level). The function isPalindrome() keeps two indices: i at the first character and j at the last. While i < j it compares the two characters; if they differ the string is not a palindrome. Otherwise i moves forward and j backward. If all pairs match, it returns 1.

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

int isPalindrome(char s[])
{
    int i = 0, j = strlen(s) - 1;
    while (i < j) {
        if (s[i] != s[j])
            return 0;
        i++;
        j--;
    }
    return 1;
}

int main(void)
{
    char str[100];
    printf("Enter a string: ");
    scanf("%99s", str);
    if (isPalindrome(str))
        printf("%s is a palindrome\n", str);
    else
        printf("%s is not a palindrome\n", str);
    return 0;
}

Sample run

Input: madam

Enter a string: madam is a palindrome

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →