Print numbers from 0 to a given number

Posted by 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


Print spelling for a given number

Write a program to reverse a string

Program to solve "Tower of Hanoi" problem

Calculate factorial of a given number

Program for printing nth Fibonacci Number

Calculate the Power of a Number (n^p)

Print numbers from a given number to 0

Check if an integer array is sorted or not

Count ways to reach the nth stair

Sum of the digits of a given number