by Dinesh Thakur

In this program, user is asked a number to enter which is stored in integer form in variable n. The value entered is say 1023.Now, this value of variable n is passed to parameter x by invoking revers() method. In revers() method, x is divided by 10 and the remainder is displayed (% returns remainder). When 1023 is divided by 10, the remainder will be 3 which is displayed on the screen. Then, again revers() is invoked with value 102/10 i.e. with 102 (because the output of dividing two integers is also an integer). 102 is assigned to variable x. Again, 102 is divided by 10 and the remainder is displayed. The remainder this time will be 2 which is displayed. Again revers() method is invoked with 10/10 i.e. which 1. And the process continues until value of x becomes 0.

Here is the Java Example for ReverseDigits:

import java.io.*;

class ReverseDigits
{
            void revers(int x)
            {
                        if(x==0) return;
                        else
                        {
                                    System.out.print(x%10);
                                    revers(x/10);
                        }
            }
            public static void main(String args[])
            throws IOException
            {
                        ReverseDigits Digit = new ReverseDigits();
                        BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
                        String h;
                        int n;
                        System.out.print("Enter a number to Reverse : ");
                        h=bf.readLine();
                        n=Integer.parseInt(h);
                        System.out.print("The  Reverse Number is : ");
                        Digit.revers(n);
            }
}

Reverse the Digits of a Number Using Recursion