Reverse the given number

In this program we will get the input from the user and reverse it using a while loop, For example, let's take a number 321 once we reverse its answer will be 123.

Step 1: First we will get the number form the user

Step 2: Then we reverse the number

Step 3: Give the result

class Reverse {

public static void main (String args[])

{

   int num, remainder, result =0;

   num = Integer.parseInt ( args[0]);

   // while loop

        while(num>0)                                // checking whether num greater than 0

          {

              remainder = num % 10;               // gives remainder

              result = result *10 + remainder;       

              num = num /10;

          } 

     System.out.println(“Reverse number is :” +result);

  }

}

Explanation of the program

Let give 321 as the input

num = 321

To get the reverse of the number we are using the while loop

Step 1 :

               while (num>0)

Here while loop will check if the given value of num is greater than 0. If it is greater than 0 then it will enter the while loop and do the further steps. Once it finishes the steps it will again check the while loop to see whether the num is greater than 0. This will continue till the num becomes 0 or less after that it breaks out of the while loop

Step 2:

               remainder = num % 10;     

Here % (modules) operator will give the remainder after doing the division.

As we have taken the no 321 when we divide it with 10 it will give the remainder 1.

So, remainder =1

Step 3:

             result = result *10 + remainder;    

When we are initializing the result we have assign the value as 0

So, result = 0*10 + 1    

       result = 1

 

Step 4:

            num = num /10;

In this step num  we get divided by 10.

Here we have taken the value of num as 321

So, num = 321/10

      num = 32

Once these 4 steps are completed, now the value of num = 32 which again go to step 1 and check the while loop whether it is greater than 0. If it’s greater than 0 steps will be continued otherwise it will come out of the loop.

When all these steps are executed we will get the reverse of the number ie. 123.

 

Leave a Reply

Your email address will not be published.