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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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).