Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Reverse of a Number (Recursive Technique) (OOP)

Updated 20 Oct 2026

Reversing a number means writing its digits in the opposite order, so 3050 becomes 0503, which is the number 503. This version is written as a class with a parameterised constructor and small methods, and the recursive method rec_rev(int n, long r) returns the finished reverse to its caller.

Definition

The reverse of a number is the number formed by writing its digits from last to first. Zeros at the end of the number become leading zeros in the reverse and are lost, so $3050$ gives $503$.

This program accepts 0 and positive numbers only. A negative number is rejected with an error message and no reverse is found. The reverse is held in a long, so even a large int such as 2147483647 (reverse 7463847412) does not overflow.

Algorithm

  1. In main, read the number into x and create the object ob with the parameterised constructor NumRev(x), which stores it in num.
  2. Call isValid(). It returns true when num is 0 or more. If it returns false, print an error message and stop.
  3. Call findReverse(), which calls rec_rev(num, 0) and keeps the returned value in reverse.
  4. rec_rev(n, r) carries the reverse built so far in its parameter r:
    • Base case: if n is 0, return r.
    • Recursive case: return rec_rev(n / 10, r * 10 + n % 10), which moves the last digit of n to the end of r.
  5. Call display() to print the number and its reverse.

Unlike a method that changes a data member, here the answer travels back up the chain of calls as the return value.

Program

The class NumRev separates the jobs: the constructor stores the number, isValid() checks it, rec_rev() reverses it recursively, findReverse() stores the result and display() prints it.

import java.util.Scanner;

/**
 * Class NumRev stores a number and finds its reverse using a recursive method
 * that returns the answer (no data member is changed by the recursion).
 */
class NumRev
{
    int num;        // the number whose reverse is to be found
    long reverse;   // the reverse of num, set after the recursive call

    /**
     * Parameterised constructor.
     * @param n the number entered by the user
     */
    NumRev(int n)
    {
        num = n;        // store the number
        reverse = 0;    // reverse is not known yet
    }

    /**
     * Checks that the number can be reversed.
     * @return true if num is 0 or more, otherwise false
     */
    boolean isValid()
    {
        return num >= 0;
    }

    /**
     * Recursive method: reverses the digits of n.
     * @param n the digits still to be processed
     * @param r the reverse built so far (starts at 0)
     * @return the complete reverse of the original number
     */
    long rec_rev(int n, long r)
    {
        if (n == 0)                              // base case: no digits left, r is the answer
            return r;
        return rec_rev(n / 10, r * 10 + n % 10); // recursive case: move last digit of n to r
    }

    /** Calls rec_rev for the stored number and keeps the result in reverse. */
    void findReverse()
    {
        reverse = rec_rev(num, 0);
    }

    /** Displays the number and its reverse. */
    void display()
    {
        System.out.println("Number  = " + num);
        System.out.println("Reverse = " + reverse);
    }

    /** main method: reads the number, creates the object and calls the methods. */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);    // reads input from the keyboard
        System.out.print("Enter a number: ");
        int x = sc.nextInt();                   // number typed by the user
        NumRev ob = new NumRev(x);              // object of class NumRev
        if (ob.isValid())
        {
            ob.findReverse();
            ob.display();
        }
        else
            System.out.println("Invalid input: enter a number that is 0 or more");
    }
}

Variable description table

VariableData TypePurpose
numintData member: the number whose reverse is to be found
reverselongData member: the reverse of num, set by findReverse()
n (constructor)intParameter of the constructor: the number entered by the user
n (rec_rev)intParameter of rec_rev(): the digits still to be processed
rlongParameter of rec_rev(): the reverse built so far
scScannerReads the number typed at the keyboard in main
xintThe number typed by the user, passed to the constructor
obNumRevObject of the class created in main to call the methods
argsString[]Command line arguments of main (not used)

Sample input and output

Sample 1

Enter a number: 3050
Number  = 3050
Reverse = 503

Sample 2

Enter a number: 0
Number  = 0
Reverse = 0

Sample 3

Enter a number: -7
Invalid input: enter a number that is 0 or more

One value per line

Dry run

Input: num = 3050. findReverse() calls rec_rev(3050, 0). The calls go down while n shrinks and r grows.

Callnn % 10Next callValue returned
rec_rev(3050, 0)30500rec_rev(305, 0)503
rec_rev(305, 0)3055rec_rev(30, 5)503
rec_rev(30, 5)300rec_rev(3, 50)503
rec_rev(3, 50)33rec_rev(0, 503)503
rec_rev(0, 503)0not usednone (base case)503

The base case returns r = 503, and every call above simply passes this value up unchanged. reverse becomes 503 and display() prints Reverse = 503, the same as the real run above.

Variations

  1. Palindrome number "Write a program to check whether a number is a palindrome, using recursion."
  2. Sum of digits "Write a recursive method to find the sum of the digits of a number."
  3. Count of digits "Write a recursive method to count the digits of a number."