Print n to 1 using Recursion

Last Updated : 27 Sep, 2025

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
redirect icon

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.

C++
#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);
}
C
#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;
}
Java
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);
    }
}
Python
def printNos(n):
    
 # base case
    if n == 0:
        return
    print(n, end=' ')
    
# recursive call
    printNos(n - 1)


if __name__ == "__main__":
    n = 3
    printNos(n)
C#
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);
    }
}
JavaScript
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
<?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

Comment