luke luke - 2 months ago 4
Java Question

Error: Cannot find symbol recursion

My problem is that it keeps saying:


cannot find symbol for n here:
System.out.println("Sum: " + sumOfArray(a, n));

How can I resolve this error?
Sorry I'm new to java TT TT


import java.util.Scanner;

public class ArraySum {
public static int sumOfArray(int[] a, int n) {
if (n == 0) {
return a[n];
} else {
return sumOfArray(a, n - 1) + a[n];

public static void main(String args[]) {
Scanner s = new Scanner(;
int[] a = new int[10];
int sum = 0;
System.out.print("Enter the elements: ");
for (int n = 0; n < 10; n++) {
a[n] = s.nextInt();
System.out.println("Sum: " + sumOfArray(a, n));


That's because you have declared n inside for. It's scope is inside for loop only.

So instead of

for (int n = 0; n < 10; n++) {
      a[n] = s.nextInt();


int n;
for (n = 0; n < 10; n++) {
      a[n] = s.nextInt();

It should do the work.


As said by Andy Turner, it's better to use a.length instead of some constant. Because when you want to change the array size from int[] a = new int[10] to int[] a = new int[20], you should also change it in the for loop. So, it's better to use the size of array in the for loop. Instead of for(n=0; n< 10; n++) use for(n=0;n<a.length;n++).

a.length gives you the size of the array.

So you can change your code to:

for (int n = 0; n < a.length; n++) 
   a[n] = s.nextInt();
System.out.println("Sum: " + sumOfArray(a, a.length));

Now you don't need to worry about changing the size in the for loop and while calling the sum().