Objective: Create a simple Palindrome checker program. The program should allow the user to enter a string and check whether the given string is a palindrome or not.
My programming level is quite insubstantial so need some criticism.
Code:
#include <stdio.h>
int main()
{
char text[100];
int i;
int fail=0;
int counter=0;
printf("Enter something to check if it is a palindrome:");
if ( (fgets(text,sizeof text, stdin)) != NULL )
{
for(i=0; text[i] != '\n'; i++)// there is a \n in the end of the text, for loop goes until it hits the \n
{
if(text[i]==' ')// counts how many characters there are
counter--;
counter++;
}
}
int k=0;
char newText[counter];//array for new text to be stored in without spaces
for(i=0; text[i] != '\n'; i++)
{
if( (text[i] !=' ') )// stores every character except spaces
{
newText[k]=text[i];
k++;
}
}
int l=0;
for (l=0; l<=k;l++)
{
if(newText[l] != newText[k-l-1])// compares the first and last character and so on
{
//printf("newText[l:%d]:%c newText[k-l %d] %c\n", l,newText[l],k-l,newText[k-l-1]);
fail=1;
l=k;
}
}
int m;
if( fail==1)
{
printf("\"");
for(m=0;m<counter; m++)// used to avoid the \n int he end of the text array
printf("%c",text[m]);
printf("\" is not a palindrome.\n");
}
else
{
printf("\"");
for(m=0;m<counter; m++)
printf("%c",text[m]);
printf("\" is a palindrome.\n");
}
return 0;
}