Java ProgramsRecursionPrint Array Using Recursion

Print Array Using Recursion in Java

beginner·  Recursion  ·  Recursion

Problem

Printing an array recursively means printing the current element and handing off the rest of the array to the next call, instead of stepping through it with a loop counter.

Given an array of integers, print each of its elements using recursion.

Input
[10, 20, 30, 40, 50]
Output
10 20 30 40 50

Java Program

Java
public class PrintArrayRecursion { static void printArray(int[] arr, int index) { if (index == arr.length) return; // every element has been printed System.out.println(arr[index]); printArray(arr, index + 1); } public static void main(String[] args) { int[] arr = {10, 20, 30, 40, 50}; printArray(arr, 0); } }

Output

10 20 30 40 50

Core Logic

Printing the element at the current index and then recursing on the next index visits every element in order, the same way a loop would, just one call per element instead of one iteration.

How It Works
  1. 1printArray(arr, index) tracks which index the current call is responsible for.
  2. 2The base case if (index == arr.length) return; fires once every index has been visited, ending the recursion without printing anything further.
  3. 3Every other call prints arr[index] first, then recurses with printArray(arr, index + 1).
  4. 4Because the print happens before the recursive call, elements are printed in the same left-to-right order they'd appear in a plain loop.
For [10, 20, 30, 40, 50], each call prints its own element before handing off to the next, producing the five values in order, one per line.
💡

Key Point: Printing before recursing is what keeps the order correct here — printing after the recursive call instead would print the array in reverse, since nothing would happen until the deepest call returned first.

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

Why: One recursive call handles one array element, so both the call count and the stack depth grow with the array's length n.

Key Concepts

recursionindex parameterbase case

Related Programs