- 2074 Asoj · 4 marks
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)
Related questions
- Switch versus user defined function · Computer Programming, chapter 5
- Check string consists of alphabet only · Computer Programming, chapter 7
- Palindrome check in FORTRAN · Computer Programming, chapter 11
- Significance of user defined functions · Computer Programming, chapter 6
- nth Fibonacci term prime check · Computer Programming, chapter 6
- How a function is defined in C · Computer Programming, chapter 6
- Convert user-defined type to basic type · Object Oriented Programming, chapter 5
- Voltage across string discs is not uniform · Power System Analysis I, chapter 2 · asked 3×
- ZOH and FOH defined; ZOH transfer function · Digital Control System, chapter 1
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3