Exercise 9
If a five digit number is input through the keyboard, write a program to reverse the number.
Solution:
/* Program to reverse the number of a five digit number */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,i, r_num=0,m=0,i;
printf(“Enter a five digit number: ”);
scanf(“%d”, &num);
/* Logical part of the program */
for(i=4; i>=0; i++)
{
m=num%10;
r_num=r_num+(m*pow(10,i));
num=num/10;
}
printf(“\nTherefore the reversed number is %d”, r_num);
getch();
}
In this one extra function is used, i.e., pow(), which is used to return power.
For example: pow(x,y) means y is the power of x and returns its value, i.e., pow(7,3) = 7^3 = 7*7*7 = 343, returns 343.
And it is defined in math.h header file, so math.h is called in the program.
Now let us understand the program with a truth-table.
Let num=54738
Thus at the end of the program we see that the reversed of the number given is obtained.
The output of the program is as follows:
Enter a five digit number: 54738
Therefore the reversed number is 83745
If a five digit number is input through the keyboard, write a program to reverse the number.
Solution:
/* Program to reverse the number of a five digit number */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int num,i, r_num=0,m=0,i;
printf(“Enter a five digit number: ”);
scanf(“%d”, &num);
/* Logical part of the program */
for(i=4; i>=0; i++)
{
m=num%10;
r_num=r_num+(m*pow(10,i));
num=num/10;
}
printf(“\nTherefore the reversed number is %d”, r_num);
getch();
}
In this one extra function is used, i.e., pow(), which is used to return power.
For example: pow(x,y) means y is the power of x and returns its value, i.e., pow(7,3) = 7^3 = 7*7*7 = 343, returns 343.
And it is defined in math.h header file, so math.h is called in the program.
Now let us understand the program with a truth-table.
Let num=54738
initial | m=0 | r_num=0 | num=54738 |
i=4 | m=54738%10 = 8 | r_num=0+(8*10^4)=80000 | num=54738/10=5473 |
i=3 | m=5473%10 = 3 | r_num=80000+(3*10^3)=83000 | num=5473/10=547 |
i=2 | m=547%10 = 7 | r_num=83000+(7*10^2)=83700 | num=547/10=54 |
i=1 | m=54%10 = 4 | r_num=83700+(4*10^1)=83740 | num=54/10=5 |
i=0 | m=5%10 = 5 | r_num=83740+(5*10^0)=83745 | num=5/10=0 |
The output of the program is as follows:
Enter a five digit number: 54738
Therefore the reversed number is 83745
Try This:
ReplyDeleteint main()
{
int a = 5678;
int temp=0,rev;
while((a%10)!=0)
{
rev =a%10;
a=a/10;
temp= temp*10+ rev;
}
return 0;
}