Q. write a program to accept a string and find out whether it is palindrome or not using pointer.
Ans.
/*program to check whether a string is palindrome or not using pointer*/
#include<stdio.h>
#include<conio.h>
int main()
{
char str[30];
char *p,*t;
printf("Enter any string : ");
gets(str);
for(p=str ; *p!=NULL ; p++);
for(t=str, p-- ; p>=t; )
{
if(*p==*t)
{
p--;
t++;
}
else
break;
}
if(t>p)
printf("\nString is palindrome");
else
printf("\nString is Not palindrome");
getch();
return 0;
}
/*************Output*************/
#include<stdio.h>
#include<conio.h>
int main()
{
char str[30];
char *p,*t;
printf("Enter any string : ");
gets(str);
for(p=str ; *p!=NULL ; p++);
for(t=str, p-- ; p>=t; )
{
if(*p==*t)
{
p--;
t++;
}
else
break;
}
if(t>p)
printf("\nString is palindrome");
else
printf("\nString is Not palindrome");
getch();
return 0;
}
/*************Output*************/
Enter any string : SHAREMARKET
String is not palindrome
Enter any string :MADAM
String is palindrome
/*********Output as snap shot*********/
Screen shot for checking whether a string is palindrome or not using pointer |
You might also like :
What is the logic behind this?
ReplyDeletefor(t=str, p-- ; p>=t; )
The logic behind this loop is comparison of character(starting character and ending character):
DeleteLet's assume str = MADAM
01234
for(p=str; *p!='\0'; p++);
for(t=str,p--; p>=t; )
In first for loop is has ; so p value is going to end of string i.e. NULL.
Now we take an another char pointer say t.
In second for loop we set t=str and p--
i.e. current values of t and p is as M and M respectively. And its run process till all checking starting and ending character by character.
Dinesh sir...why you are decrementing the value of p in the second for loop and again in the later part of the program
Deleteif (*p == *t) is true , then one more time p is decremented?? please explain the reason
ReplyDeletewhat is the logic behind this?
{
if(*p==*t)
{
p--;
t++;
}
else
break;
@Rubi,
Delete*p==*t is comparison of character.
*p represent the last character of string, and
*t represent the beginning character of string
and both are equal then
p decrease to one i.e. second last character, and
t increase to one i.e. second value of character.
Hence, this condition check equality both side(i.e. left side and right side) character one by one, If this condition found any unequal then compiler goes to "else" part execute break; statement and next its check "string is palindrome or not" using t>p.
I executed this..
ReplyDeleteCompilation : Passed
Test Case 1 Passed
Input Expected Output Actual Output
1 2 3 4 5 5 4 3 2 1 yes yes
Test Case 2 Wrong Answer
Input Expected Output Actual Output
1 2 3 4 5 6 7 8 9 0 no yes
it meant that the string ":1 2 3 4 5 6 7 8 9 0" is a palindrome
why so?
this code gives the same answer for all the strings...i.e. String is aplindrome
ReplyDelete