Given an integer n. Print numbers from n to 1 using recursion.
Examples:
Input: n = 3
Output: [3, 2, 1]
Explanation: Print numbers in reverse order from n down to 1.Input: n = 10
Output: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Explanation: Print numbers in reverse order from n down to 1.
Try it on GfG Practice
Approach:
The idea is to use recursion to print numbers in decreasing order. We first check the base case: if n becomes 0, we stop further recursive calls. Otherwise, we first print the current number n and then make a recursive function call with n-1. This way, the function keeps reducing the problem size until it reaches the base case.
#include <iostream>
using namespace std;
void printNos(int n){
// base case
if (n == 0)
return;
cout << n << " ";
// recursive call
printNos(n - 1);
}
int main(){
int n = 3;
printNos(n);
}
#include <stdio.h>
void printNos(int n){
// base case
if (n == 0)
return;
printf("%d ", n);
// recursive call
printNos(n - 1);
}
int main(){
int n = 3;
printNos(n);
return 0;
}
class GFG {
static void printNos(int n){
// base case
if (n == 0)
return;
System.out.print(n + " ");
// recursive call
printNos(n - 1);
}
public static void main(String[] args){
int n = 3;
printNos(n);
}
}
def printNos(n):
# base case
if n == 0:
return
print(n, end=' ')
# recursive call
printNos(n - 1)
if __name__ == "__main__":
n = 3
printNos(n)
using System;
class GFG {
static void printNos(int n){
// base case
if (n == 0)
return;
Console.Write(n + " ");
// recursive call
printNos(n - 1);
}
public static void Main(){
int n = 3;
printNos(n);
}
}
function printNos(n){
// base case
if (n == 0)
return;
process.stdout.write(n + " ");
// recursive call
printNos(n - 1);
}
//Driver code
var n = 3;
printNos(n);
<?php
function printNos($n){
// base case
if($n > 0){
echo $n, " ";
// recursive calls
printNos($n - 1);
}
return;
}
// Driver code
$n=3;
printNos($n);
?>
Output
3 2 1
Time Complexity: O(n)
Auxiliary Space: O(n), Recursive Stack Space