Problem Statement
Write a recursive function to print numbers from n to 1 in decreasing order. The function should take an integer n as input and print the numbers linearly from n down to 1.
Examples
Example 1:
Input: n = 5
Output:
5
4
3
2
1Example 2:
Input: n = 7
Output:
7
6
5
4
3
2
1Different Approaches
1️⃣ Top Down Approach
Code:
#include <iostream>
using namespace std;
void printNumbers(int n) {
// Base case: when n reaches 0, stop the recursion.
if (n == 0)
return;
// Print the current number
cout << n << endl;
// Recursive call with n-1
printNumbers(n - 1);
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
// Start recursion from n
printNumbers(n);
return 0;
}
Explanation:
- The function
printNumbers(int n)prints the numbern, and then calls itself withn-1to print the next number. - The base case (
if (n == 0)) ensures that the function stops when it reaches zero, avoiding infinite recursion.
Complexity Analysis:
- Time Complexity:
- The time complexity is
O(n), wherenis the input value. - The function is called
ntimes before hitting the base case.
- The time complexity is
- Space Complexity:
- The space complexity is
O(n)because each recursive call uses stack space, and the maximum depth of recursion isn.
- The space complexity is
