-1

The main method calls sum and has to return the sum of the array.The program aims at finding sum of array without using any loop. Not able to detect the error.

The code for Sum of array using recursion:

import java.util.Scanner;


public class X{


public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int l1,j,sum=0;
    try{
    System.out.println("Enter length of array: ");
    l1= sc.nextInt();
    int[] s1=new int[l1];
    System.out.println("Enter array elements: ");
    for(j=0;j<l1;j++)
        s1[j]=sc.nextInt();

    sum=sum(s1,0);
    System.out.println("Sum = "+sum);

    }
    finally{ sc.close();}

}

public static int sum(int[] a,int i){

    if(i>=a.length)
        return 0;

    return a[i]+sum(a,i++);

}   

}
Aishwarya R
  • 647
  • 2
  • 12
  • 25

1 Answers1

0

i++ returns i before the increment, so you recursing with the same i.

Replace i++ with ++i

Porz
  • 183
  • 3
  • 15