i know how to find palindrome and also how to find reverse of string using for loop. but i wish to do it within a loop (for) using flag. can u please tell me how to use flag in c . my code is as follows

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j; int d;  int d1;int flag=0;
char str[10];
char str2[10];
char str3[10];
clrscr();
printf("enter a string");
scanf("%s",str);
strcpy(str2,(strrev(str)));
for(i=0;i<=d-1;i++)
{
if(str2[i]==str[i])
flag=1;
}
if(flag==1)
printf("palindrome");
else
printf("not palindrome");
getch();
}

thank you in advance

Recommended Answers

All 3 Replies

>>for(i=0;i<=d-1;i++)
Why not just i < d to avoid subtracting 1 from d on every loop iteration.

And it might be better to use another counter intead of all those subtractions. Note also that you don't need the str2 variable.

int x;
x = strlen(str) - 1;
for(i = 0; flag == 0 && i < d; i++, x--)
{
   if( str[i] != str[x] )
   {
       flag = 1;
   }
}

The string is only a palindrome if the characters match all of the way through. Your flag should be changed in the loop if the test fails, and you can also break from the loop because there's no need to continue checking a failed palindrome:

int different = 0;

for (i=0; i < d; i++)
{
    if (str2[d-i-1] != str[i])
    {
        different = 1;
        break;
    }
}

if (!different)
    printf("palindrome\n");
else
    printf("not palindrome\n");

If the loop goes all the way to the end, it's a palindrome. Another way to do the check without the flag is to use i. If i gets to d, it's a palindrome:

for (i=0; i < d; i++)
{
    if (str2[d-i-1] != str[i]) break;
}

if (i == d)
    printf("palindrome\n");
else
    printf("not palindrome\n");

Know one thing : To assure that its a palindrome you need to check the whole string and get positive results.But to say its not a palindrome you just need one dissimilarity in your check. So you can just do this...

d=strlen(str)-1; 
for(i=0;i<=d;i++)
{
     if(str2[d-i]!=str[i])
    {
         flag=1;
         break;
    }
}
if(flag==0)
            printf("palindrome");
else
            printf("not palindrome");

Usage of extinct headers and functions clrscr() @ Ancient Dragon :

int x;
x = strlen(str) - 1;
for(i = 0; flag == 0 && i < d; i++, x--)
{
if( str != str[x] )
{
flag = 1;
}
}

That should be x not d ;).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.