Questions: Top-30-c-programs-asked-in-interview_6304.html
9. Write a program to check whether the given number is a palindromi c number.
If a number, which when read in both forward and backward way is same, then such a number is called a palindrome number.
Program:
#include
int main(){
int n, n1, rev = 0, rem;
printf("En ter any number: \n");
scanf("%d" ,&n);
n1 = n;
/* logic */
while (n>0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev){
printf("Gi ven number is a palindromi c number");
}
else{
printf("Gi ven number is not a palindromi c number");
}
return 0;
}
Output:
Enter any number: 121
Given number is a palindrome
Explanatio n with an example:
Consider a number n=121, reverse=0, remainder;
number=121
now the while loop is executed /* the condition (n>0) is satisfied */
/* calculate remainder */
remainder of 121 divided by 10=(121%10 )=1;
now reverse=(r everse*10) +remainder
=(0*10)+1 / * we have initialized reverse=0 */
=1
number=num ber/10
=121/10
=12
now the number is 12, greater than 0. The above process is repeated for number=12.
remainder= 12%10=2;
reverse=(1 *10)+2=12;
number=12/ 10=1;
now the number is 1, greater than 0. The above process is repeated for number=1.
remainder= 1%10=1;
reverse=(1 2*10)+1=12 1;
number=1/ 10 / * the condition n>0 is not satisfied,co ntrol leaves the while loop */
Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a
palindrome number.
9. Write a program to check whether the given number is a palindromi c number.
If a number, which when read in both forward and backward way is same, then such a number is called a palindrome number.
Program:
#include
int main(){
int n, n1, rev = 0, rem;
printf("En ter any number: \n");
scanf("%d" ,&n);
n1 = n;
/* logic */
while (n>0){
rem = n % 10;
rev = rev * 10 + rem;
n = n / 10;
}
if (n1 == rev){
printf("Gi ven number is a palindromi c number");
}
else{
printf("Gi ven number is not a palindromi c number");
}
return 0;
}
Output:
Enter any number: 121
Given number is a palindrome
Explanatio n with an example:
Consider a number n=121, reverse=0, remainder;
number=121
now the while loop is executed /* the condition (n>0) is satisfied */
/* calculate remainder */
remainder of 121 divided by 10=(121%10 )=1;
now reverse=(r everse*10) +remainder
=(0*10)+1 / * we have initialized reverse=0 */
=1
number=num ber/10
=121/10
=12
now the number is 12, greater than 0. The above process is repeated for number=12.
remainder= 12%10=2;
reverse=(1 *10)+2=12;
number=12/ 10=1;
now the number is 1, greater than 0. The above process is repeated for number=1.
remainder= 1%10=1;
reverse=(1 2*10)+1=12 1;
number=1/ 10 / * the condition n>0 is not satisfied,co ntrol leaves the while loop */
Program stops here. The given number=121 equals the reverse of the number. Thus the given number is a
palindrome number.
0 comments:
Post a Comment