Print numbers from 0 to a given number

Posted by N.K. Chauhan on Mar 31, 2024

A number "n" is given, the task is to print numbers from 0 to n using recursion.

Example 1: Print numbers from 0 to 5

Input: 5
Output:

0
1
2
3
4
5


Solutions

Method 1: Recursion

We can solve this problem using recursion easily, all we need to do is, make a "recursive call with n-1" and "print n" while "breaking recursion if n < 0" (Base Condition).

package com.cb.recursion;

/*
 * Input: 5
 * Output: 0,1,2,3,4,5
 * */
public class R2_PrintNumbers {
    public static void print(int n) {
        // base condition
        if (n < 0) return;
        
        // recursive call
        print(n - 1);

        // work
        System.out.println(n);
    }

    public static void main(String[] args) {
        print(5);
    }
}

Complexity
The time complexity of given solution is O(n) and space complexity is O(1).

Related


Check if an integer array is sorted or not

Print numbers from a given number to 0

Count ways to reach the nth stair

Write a program to reverse a string

Calculate the Power of a Number (n^p)

Sum of the digits of a given number

Program to solve "Tower of Hanoi" problem

Program for printing nth Fibonacci Number

Calculate factorial of a given number

Print spelling for a given number