I wrote a code to find out the missing palindrome alphabet in a string. It passes a few test cases and fails a few.
I'm not sure where I made a mistake and everything seems right in the code.
The code is,
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include<ctype.h>
int main()
{
char palindromeChar[100];
fgets(palindromeChar, 100, stdin);
int revCtr = strlen(palindromeChar) - 1, fwdCtr = 0, counter;
for(counter = 0; counter < strlen(palindromeChar)/2; counter++) {
if(palindromeChar[fwdCtr] != palindromeChar[revCtr]) {
printf("%c", palindromeChar[fwdCtr]);
break;
}
++fwdCtr;
--revCtr;
}
}
When it comes to inputs like,
malayaam
It prints out,
m
which is the first character in the case, but what the actual condition is if the forward character is not equal to the reverse character, it's asked to be print.
Why does it prints the first character itself? What's the problem and the fix?
fgets() includes the newline char '\n' in the array, so you need to skip that character.
int revCtr = strlen(palindromeChar) - 1
to
int revCtr = strlen(palindromeChar) - 2
Good point in the comment below about double checking for newline char first, so instead, leave revCtr as is and
int revCtr = strlen(palindromeChar) - 1, fwdCtr = 0, counter;
if (palindromeChar[revCtr] == '\n') {
revCtr--;
}