You are here:   HomeJava ProgrammingJava MethodsReverse the Digits of a Number Using Recursion | Java Example
by Dinesh Thakur Category: Java Methods

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





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular