a program for palindrome in C

well i have created a program but my logic is little bad ,,
can any one help to improve my logic a little please
(i cant understand c++,, i am beginner to C )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<conio.h>
#include<stdio.h>
int i=0,j=0,k=0,a;
void main ()
{
char arr[200];

while ( (arr[i]=getche()) != '\r')
{
		i++;
		a++;
}
for (i=0;i<=(a/2);i++)                         /*logic of this two loops are , we will take one loop from start to half hand other from end to half, then compare both*/ 
{											   /*these two loops will repeat equally*/
	for(j=(a-1);j>=a/2;j++)
	{
		if (arr[i]==arr[j])
		{
			
				printf("this string is pelindrome");
			
		}
	}
}
getch()
Last edited on
Hi

Could you edit your orig. post to sort out the formatting. In particular the indenting (of scopes). It's quite hard to read at the mo'.

But from what I can see through the "murk"...

#1 a is not inititlized (to 0), so it's been incremented from an unknown value.

suggestion: use single declaration per line to make this clearer

#2 main should return int (a void return is non-standard)

#3 you only need one loop. replace your two by a single one

these two loops will repeat equally

Not true! To start with, the second loop is incrementing when it should be decrementing!

But when j-- is used instead of j++, it is still not right as the j loop is nested inside the i loop. If you log the comparisons made, you will see it tries (for "hello")

i = 0, j = 4
i = 0, j = 3
i = 0, j = 2
i = 1, j = 4
i = 1, j = 3
i = 1, j = 2
i = 2, j = 4
i = 2, j = 3
i = 2, j = 2

which is not what you need here!

#4 the point you say it's palindrome is not right: you only know it it is one at the end of the loop(s)

#5 your input code looks unnecessarily complicated. see
http://www.cplusplus.com/reference/clibrary/cstdio/gets/

And while I was at it, I'd give some of you variables better names!

Andy
Last edited on
getche is not a standard C function. So it is better if you will not use it.
Also your code is invalid. You should use a single loop to compare two parts of the character array.
Last edited on
Topic archived. No new replies allowed.