Code Box
------------------------------------------
/*Program to find reverse of a number by do while loop in C*/
#include<stdio.h>
#include<conio.h>
void main()
{
int num,num1,rem,newnum;
clrscr();
newnum=0;
printf("\n\tReverse Number maker");
printf("\n-------------------------");
printf("\nEnter a number:");
scanf("%d",&num);
num1=num; //to save actual number
do
{
rem=num1%10;
num1=num1/10;
newnum=newnum*10+rem;
}while(num1>=1);
printf("\nReverse of number is : %d",newnum);
getch();
}
----Explanation------------------------------------------------------
By reverse of any number means just reversing the sequence of digits of given number.
For example: 1234 is a given number than it's reverse is 4321.
In above program we use do while loop to find reverse of number.
- we use num1=num to protect value of num in our program because while calculating reverse we divide it til it becomes 1.
- rem=num1%10; gives us remainder each time means the last digit because of modulus operator.
- num1=num1/10; reduce the value of num1 by 10 each time. means removes last single digit every time.
- newnum=newnum*10+rem; creates the reverse value by multiplying 10 to previous remainder.
On initial we take num1=1234 as input and newnum=0.
at do while loop :
first time
rem=1234%10 =4
num1=1234/10= 123
newnum= 0*10+4 = 4
test condition: num1>=1 => true as 123>=1
--------------------------
second time
rem=123%10 =3
num1=123/10= 12
newnum= 4*10+3 = 43
test condition: num1>=1 => true as 12>=1
-------------------------
Third time
Third time
rem=12%10 =2
num1=12/10= 1
newnum= 43*10+2 = 432
test condition: num1>=1 => true as 1>=1
-------------------------
Forth time
rem=1%10 =1
num1=1/10= 0
newnum= 432*10+1 = 4321
test condition: num1>=1 => false as 0>=1
So, we get the required reversed value.
Code Box C is a blog specially for all who want to learn C language or any other programming language. I just try to get you the basic concept behind the given problem because the concept to solve any given problem in all languages is always same. It will help you to speedup or boost your learning speed as well as your strategy building skills if you know the actual concept.
Code Box C is a blog specially for all who want to learn C language or any other programming language. I just try to get you the basic concept behind the given problem because the concept to solve any given problem in all languages is always same. It will help you to speedup or boost your learning speed as well as your strategy building skills if you know the actual concept.
No comments:
Post a Comment