Print Reverse of a number in java

Printing reverse of a number


Steps to do it:-
1.take 3 integers r,n,sum=0 (n is for user input number sum is for calculating the addition step an r is for remainder)

2. take the value from user

3.start the While loop
while(n>0) then do this
{
r=n%10;// it will extarct the last number of the given number

sum=sum*10+r; 

n=n/10;// it will eliminate the last number of the user input number
}
 explanation:-
if user input 123 then
1st loop run
r=123%10 =3 (1st loop run)
sum=0*10+3= (3 for 1st loop run)
n=n/10 =123/10 = 12 (for first loop run)

2nd loop run

r=12%10=2
sum=3*10+2=32
n=n/10=12/10=1

3rd run
r=n%10=1%10=1
sum=32*10+1=321
n=n/10=1/10=0
the loop will be terminated 
print"the reverse is "+sum

4.save and rrun


The Source Code

import java.util.Scanner;
class reverse
{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int r,n,sum=0;// r is for remainder n is for user input number and sum is for calculating the addition
        System.out.println("enter the number");
        n=s.nextInt();
        while(n>0)
        {
            r=n%10;
            sum=sum*10+r;
            n=n/10;
        }
        System.out.println("the reverse is "+sum);
    }
}

OUTPUT


Watch My Video

 

Comments

Popular Posts