A palindrome is a sequence of characters or numbers, which reads the same both forward and backward. Example: madam, kayak, 12321.
//Program to check palindrome
#include<stdio.h>
#include<conio.h>
main()
{
int choice,i=0,j,n,num,rev=0;
char *str;
clrscr();
do
{
printf("1. String Palindrome\n 2. Number Palindrome\n");
printf("Enter your choice\n");
scanf("%d",&choice);
switch (choice)
{
case 1: printf("Enter the string\n");
scanf("%s",str);
while (str[++i] !='\0'); // To count the number of characters
i=i-1;
for(j=0;j<=i;j++,i--) // j starts from first character and i starts from last character
if (str[j]!=str[i])
break;
if (j>i)
printf("The given string is palindrome\n");
else
printf("The given string is not palindrome\n");
break;
case 2: printf("Enter the number\n");
scanf("%d",&n);
num=n; //the given number is needed for final comparison; hence stored in num
rev=0;
while (n>0)
{
rev=rev*10+n%10;
n=n/10;
}
if (num==rev)
printf("The given number %d is palindrome\n",num);
else
printf("The given number %d is not palindrome\n",num);
break;
default: printf("Wrong choice\n");
}
printf("Do you want to continue? 1. Yes 2. No\n");
scanf("%d",&choice);
}while (choice==1);
getch();
}
/*
OUTPUT
------------
1
Enter the string
mary
The given string is not palindrome
Do you want to continue? (y/n)1. Yes 2. No
1
1. String Palindrome
2. Number Palindrome
Enter your choice
2
Enter the number
12321
The given number 12321 is palindrome
Do you want to continue? (y/n)1. Yes 2. No
1
1. String Palindrome
2. Number Palindrome
Enter your choice
2
Enter the number
1234
The given number 1234 is not palindrome
Do you want to continue? (y/n)1. Yes 2. No
2
*/
No comments:
Post a Comment