Print Array Using Recursion in Java
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.
Java Program
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
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.
- 1
printArray(arr, index)tracks which index the current call is responsible for. - 2The base case
if (index == arr.length) return;fires once every index has been visited, ending the recursion without printing anything further. - 3Every other call prints
arr[index]first, then recurses withprintArray(arr, index + 1). - 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.
[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.
Why: One recursive call handles one array element, so both the call count and the stack depth grow with the array's length n.