-3
import java.util.Scanner;

public class recursion_4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a[] = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        printArray(a, 0);
        sc.close();
    }

    static void printArray(int arr[], int i) {
        if (i == arr.length) {
            return;
        }
        printArray(arr, ++i);
        System.out.println(arr[i]);
    }
}

I am try to print array element using recursion.

But it give error of arrayIndex Out of bound.

Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • You've almost got it. when you call printArray(arr, arr.length - 1); The if statement passes, the call to printArray is called with arr.length, which is fine, but then you're calling arr[i] but i == arr.length. Switch the order, or even better just use i+1. – matt Nov 23 '22 at 17:06

2 Answers2

1

Replace ++i with i+1

You are incrementing the value of local variable in function. Instead of incrementing, send next value to other function as you will use that local variable value while printing in your function.

arctic_fox
  • 24
  • 4
0

++i increments the value - it actually changes it (and evaluates as the updated value.)

++i, i++ and the subtle distinction between them has been the cause of many and frustrating bugs. This is just my opinion, but I advise never using either one of them except as a single-line statement when you need to increment something. The brevity isn't worth the risk of bugs.

So if you enter printArray with i=arr.length-1, then you get past your i guard, increment i, make the recursive call (which returns), and then try to access `arr[arr.length - 1 + 1], which is out of bounds.

If you're just learning about recursion, you might be confused at how local variables and returns work in a method. Each time you call a method, that's a new stack frame (a section of memory) with completely different values for its local variables, and which returns independently. i is not "i in every usage of the method named printArray", it's only "i in the current application of the method printArray." Similarly when you return, you cease to run the current application of printArray, but not every application.

Sorry if that part's all stuff you know - I find it's one of those things that's completely mind boggling to people starting out, and then becomes completely obvious a week later.

Edward Peters
  • 3,623
  • 2
  • 16
  • 39