Subscribe to:
Post Comments (Atom)
CodeShikhi - The World for Programmers, প্রোগ্রামিং,Learn Programming,Learn Javascirpt | C | C++ | Python | OOP,Learn Programming in Bangla,Bangla Programming Tutorial,Leetcode Problem Solution,BEE Problem Solution,C Programming in Bangla,C in Bangla,Javascript tutorials,C Programming Bangla Tutorial, URI Online Judge Solution in C C++ Python,JavaScript Full Tutorials , OOP Tutorial in C++, Object Oriented Programming in C++,Learn OOP in C++,C Programming Exercise,C Programming Example with Code
#include<stdio.h>
int main()
{
int dummy,n,rev=0,x;
printf("Enter a number\n");
scanf("%d",&n);
dummy=n;
while(n>0)
{
x=n%10;
rev=rev*10+x;
n=n/10;
}
printf("The reverse of %d is %d\n",dummy,rev);
}
Here we did initialization for,
dummy----->To store the entered value(i.e 'n') as you will come to know at the end of the program.
n----------->To store number given by user.
rev----->To store the reverse of a number. It is initialized to zero.
x---------->To store n%10.
First of all we got a number 'n' from user and then stored it in a dummy variable called as 'dummy' for restoring the value.(remember this point).
Now the main logic comes here:-
let the number 'n' be 321 and as 321>0,while loop gets executed
then x=321%10--->which is 1.
rev=0*10+1-------->1
n=321/10--------->32
The rev for the first loop execution is rev=1.
Now the number 'n' has become '32' and n>0,while loop executes for 2nd time.
then x=32%10--->which is 2.
rev=1*10+2-------->12
n=32/10--------->3
The rev when loop executed second time is rev=12.
Now the number 'n' has become '3' and n>0,while loop executes for 3rd time
then x=3%10--->which is 3.
rev=12*10+3-------->123
n=3/10--------->0
The rev when loop executed third time is rev=123.
Now as the number in variable 'n' is 0 which is not n>0 then the loop terminates. Then the final reverse is '123'.
So now I hope you understood why the dummy variable is used.It is because the value in 'n' becomes 0 at the end of the program so for restoring this value to print at the end we used 'dummy'(as from the 2nd point).
Finally it prints the value in 'rev'.
Previous Post:
0 Response to Write a C Program to Print The Reverse of Given Number | C Programming Examples
Post a Comment