Recursion: Print N to 1 using recursion

Problem Statement:

You are given an number N, you need to print values from N to 1 using recursion.

Example:

Input: N = 5

Output: 5 4 3 2 1

Solution Explanation:

Solution is very simple.

Time Complexity: O(n)
Space Complexity: O(n)

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

void solution(int n){
    
    if (n == 0)
        return;
   
    cout << n << " ";
    
    solution(n - 1);
}

int main(){
    
    int n = 5;
    
    solution(n);
}

Output

5 4 3 2 1
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *