Print numbers from a given number to 0

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

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

Example: Print numbers from 5 to 0

Input: 5
Output:

5
4
3
2
1
0


Solutions

Method 1: Recursion

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

package com.cb.recursion;

/*
 * Input: 5
 * Output: 5,4,3,2,1,0
 * */
public class R1_PrintNumbers {

    public static void print(int n) {
        // base condition
        if (n < 0) return;

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

        // recursive call
        print(n - 1);
    }

    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

Count ways to reach the nth stair

Calculate factorial of a given number

Calculate the Power of a Number (n^p)

Program for printing nth Fibonacci Number

Program to solve "Tower of Hanoi" problem

Sum of the digits of a given number

Print spelling for a given number

Print numbers from 0 to a given number

Write a program to reverse a string