Skip to main content

Java program to find the reverse the number.

                Let us see the java program to reverse the number. 

Content.
  1. What is Reverse the number.
  2. Logic for program.
  3. Program.
  4. Explanation.
  5. Output.


What is Reverse the number?

             Revering number means the order of the number changer, it displays the number from backward.
Example:
                    our Input: 9874
                       Output: 4789


Logic for the Program.
  • We need to display the last number first so, we divide(%) the number by 10 and take the reminder as answer.
  • So, when we use that in a loop we get the Reversed number.


Program

import java.io.*;
class reve
{
 public static void main(String arg[]) throws IOException
  {
    int n,r,s=0;
    InputStreamReader read = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(read);
    System.out.println("Enter the number");
    n=Integer.parseInt(in.readLine());
       while(n!=0)
         {
            r=n%10;
            s=s*10+r;
            n=n/10;
         }
    System.out.println("The reversed number of is" +s);
  }
}


Explanation.
  • We have given the class name has reve.
  • public static void main(String arg[]) refers to add a method i.e array of strong method to the program.
  • int n,r,s is declaring the variable, s is declared to store 0. 
  • InputStreamReader read = new InputStreamReader(System.in); we create this object because we need to give the value to variable at the time of execution, this is a one of the way to give value to a variable.
  • BufferedReader in = new BufferedReader(read); we create this object because, we need a buffer to store the value of the variable.
  • n=Integer.parseInt(in.readLine()) is used to convert array of numbers to primitive integer.
  • Now, we have to give condition which satisfies all the above int the logic for the program. I choose, While loop with n!=0 (n not-equal to 0)condition.
  • n is the number we give.
  • inside the loop ,
      • to get reverse number, r=n%10
      • to end the loop after reverse the number, s=(10*s)+r;
      • to keep continue the loop for next number, n=n/10;
  • System.out.println is used to display the given in output screen(make sure S in System is capital)


Know more about while loop here.


Output:

       Compile : javac reve.java
       Run        : java reve
       Enter the number
       9514
      The reversed number of is 4159.

      Compile : javac reve.java
       Run        : java reve
       Enter the number
     32165
      The reversed number of is 56123.



Comments