Print Numbers from 1 to N using Recursion in Java

Introduction

Printing numbers from 1 to n is very simple in Java. We can use loops.

But the challenge here is, can we do it using recursion?

Before we use recursion let us understand basics about recursion.

Just a brief introduction about recursion

Recursion is a programming technique where a function calls itself in order to solve a problem. Function keeps calling itself with smaller instances of the problem until it reaches a base case.

Printing Numbers 1 to n Using Recursion

We can print from 1 to n without using loop in java

Let say we want to print numbers from 1 to 10. You are given n as 10.

Since n=10 , we need to start from 10 to go back to 1

10–>9–>8–>7–>6–>5–>4–>3–>2–>1

Function should call itself with n-1 until it reaches 0. Since we want to print from 1 to 10 we should print only we reach the base case.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package recursion;

public class PrintNumbers {

    public static void main(String[] args) {
        printNumbers(10);
    }

    public static void printNumbers(int n){
        if(n<=0)
            return;

        printNumbers(n-1);
        System.out.println(n);
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
1
2
3
4
5
6
7
8
9
10

What happens if we write print statement before printNumbers(n-1)?

In such scenario, since we are calling from number from n to 1 and printing it first, order of number printed will be from n to 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package recursion;

public class PrintNumbers {

    public static void main(String[] args) {
        printNumbers(10);
    }

    public static void printNumbers(int n){
        if(n<=0)
            return;

        System.out.println(n);

        printNumbers(n-1);

    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
10
9
8
7
6
5
4
3
2
1

That wraps up our tutorial on Java recursion and printing numbers using recursion.