Reserving a number simply involves
1)Intially taking the remainder as 0
2)Calculating and storing remainder of a number when divided by 10.
3)Multiplying the immediate remainder by 10 and adding it to previous value of remainder.
4)Dividing the number by 10
5)Repeating the above steps until number becomes 0.
For example
taking all variables as integers so that fractional part is truncated during division
number=532 (not equal to 0)
immediate remainder=number%10=532%10=2
previous remainder= (previous remainder*10)+immediate remainder=0*10+2=2
number=number/10=532/10=53
number=53 (not equal to 0)
Repeat steps
immediate remainder=number%10=53%10=3
previous remainder=(previous remainder*10)+immediate remainder=2*10+3=23
number=number/10=53/10=5
number=5 (not equal to 0)
Repeat steps
immediate remainder=number%10=5%10=5
previous remainder=(previous remainder*10)+immediate remainder=23*10+5=235
number=number/10=5/10=0
number=0
Stop loop
#include<stdio.h>
int main()
{
int num, num_copy, rem,rev;
printf("\nEnter the number to be reversed:");
scanf("%d",&num);
num_copy=num;
rem=0;
rev=0;
while(num!=0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
printf("\nReverse of %d is %d",num_copy,rev);
return 0;
}
1)Intially taking the remainder as 0
2)Calculating and storing remainder of a number when divided by 10.
3)Multiplying the immediate remainder by 10 and adding it to previous value of remainder.
4)Dividing the number by 10
5)Repeating the above steps until number becomes 0.
For example
taking all variables as integers so that fractional part is truncated during division
number=532 (not equal to 0)
immediate remainder=number%10=532%10=2
previous remainder= (previous remainder*10)+immediate remainder=0*10+2=2
number=number/10=532/10=53
number=53 (not equal to 0)
Repeat steps
immediate remainder=number%10=53%10=3
previous remainder=(previous remainder*10)+immediate remainder=2*10+3=23
number=number/10=53/10=5
number=5 (not equal to 0)
Repeat steps
immediate remainder=number%10=5%10=5
previous remainder=(previous remainder*10)+immediate remainder=23*10+5=235
number=number/10=5/10=0
number=0
Stop loop
#include<stdio.h>
int main()
{
int num, num_copy, rem,rev;
printf("\nEnter the number to be reversed:");
scanf("%d",&num);
num_copy=num;
rem=0;
rev=0;
while(num!=0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
printf("\nReverse of %d is %d",num_copy,rev);
return 0;
}
No comments:
Post a Comment