Home C Programming Episode 11: Reverse A Number Program

Episode 11: Reverse A Number Program

1
SHARE

Take A Number, Reverse It.

Explanation:

Reversing A number is very tricky concept but it is very easy to implement. Take a value from user, store it in variable ‘n’.

Now Apply logic:

let say n is 1234 and we want 4321

We know:

1234%10=4

1234/10=123

What we should do such that first it will be 4 then 43 then 432 then 4321?

Take a variable rev;

rev=rev+n%10 //0+4=4;

n=n/10 // 123

Yo! we got first iteration but what about second iteration?

There would be problem right?

See in second iteration  rev=rev+n%10 // 4+3=8

n=n/10; //12

This is wrong!!!!!!!! So what should we do such that it will be ’43’

So you got it right we should write ‘ rev = (rev *10) + n%10;’

Now you know how to apply logic.

Let say my number is 1234

First:

rev=(rev*10)+n%10 //(0*10)+4=4

n=n/10 //1234/10=123

Second:

rev=(rev*10)+n%10 //(4*10)+3=43

n=n/10 //123/10=12

Third:

rev=(rev*10)+n%10 //(43*10)+2=432

n=n/10 //12/10=1

Fourth:

rev=(rev*10)+n%10 //(432*10)+1=4321

n=n/10 //1/10=0

 

if n is 0 then exit the loop.

 

This is how you learn the logic to solve the problem.

 

code:

#include <stdio.h>
#include <conio.h>

void main()
{
int n,rev=0;

printf(“Enter A Number:”);
scanf(“%d”,&n);

while(n>0)
{
rev=(rev*10)+n%10;
n=n/10;
}

printf(“\n Reverse: %d”,rev);
getch();
}

Output:

Enter A Number:1232

Reverse: 2321

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here