# Reversal using recursion

In this post I would be discussing reversal using recursion. Our objective is to reverse a positive integer using a recursive technique. Since I consider the use of a global variables (that is the variables declared outside the recursive function) in recursion as a bad programming practise, our recursive function would be using two arguments. One argument would be for the number to be reversed and the other argument would be for the current reverse (or in other words the- interim reverse)  number. Each recursive call would remove the last digit from the number and this would go on till the number becomes equal to zero. Once the number becomes zero, the interim reverse number would become the reverse number and would be returned. In order to make things simple for the end user we would make a wrapper function by overloading the reverse function(). This reverse function would accept only one integer argument, that is, the number to be reversed and would then invoke the recursive function reverse() with the correct initial values.

The Java program for reversal using recursion is as follows:

```class MyNumber{
public static int reverse( int n ){
return reverse(n,0);
}
private static int reverse( int n, int rev ){
if( n==0 ) return rev;
else  return reverse(n/10,(rev*10)+(n%10));
}
public static void main( String args[] ){
System.out.println( reverse( 12345) );
}
}
```

In order to understand the logic students may add the following line just before the exit condition of the recursive reverse() function:

`System.out.println("n="+n+" rev="+rev);`

As usual, the main function has purposely been kept to minimum and its expected that students will write appropriate input/output statements as per the requirement.

Students must understand that the use of recursion is discouraged for these types of problems as it’s more expensive in terms of time and memory. It’s more of an intellectual exercise.

Follow me

### Vinay Singh

Computer Teacher at Saint John's Academy
I am a GNU/Linux enthusiast and a computer science teacher by profession based at Allahabad, India. My hobbies include reading (mostly computer related stuff) and photography.
Follow me