Java ProgramsRecursionPrint Numbers in Reverse Using Recursion

Print Numbers in Reverse Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

Counting a recursive parameter downward instead of upward reverses the order the base case is reached in, which reverses the order numbers get printed in too.

Given a number n, print every integer from n down to 1 using recursion.

Input
n = 5
Output
5 4 3 2 1

Java Program

Java
public class PrintNumbersReverseRecursion { static void print(int n) { if (n < 1) return; // descended past 1 — nothing left to print System.out.println(n); print(n - 1); } public static void main(String[] args) { int n = 5; print(n); } }

Output

5 4 3 2 1

Core Logic

Printing the current number and then recursing on one less than it, instead of one more, walks the sequence downward instead of upward.

How It Works
  1. 1print(n) takes only the current number, since counting down needs no separate upper bound.
  2. 2The base case if (n < 1) return; stops the recursion once it descends past 1.
  3. 3Each call prints n first, then calls print(n - 1) to handle the next number down.
  4. 4The initial call print(n) starts the countdown at the original value.
For n = 5, the calls print 5, 4, 3, 2, 1 in that order, each call printing before recursing further.
💡

Key Point: Only the direction of the parameter change — n - 1 instead of i + 1 — separates this from the ascending version; the base case and print-then-recurse shape are otherwise identical.

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

Why: One recursive call handles each number printed, and the call stack grows to depth n before the base case is reached and the frames start returning.

Key Concepts

recursionbase casedescending parameter

Related Programs