Sum of array using recursion! (Error: StackOverflowError)
Sum of array using recursion! (Error: StackOverflowError)
main 方法调用 sum 并且必须 return 求和 array.The 程序的目的是在不使用任何循环的情况下找到数组的和。无法检测到错误。
使用递归求数组求和的代码:
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++);
}
}
i++ returns i 在增量之前,所以你用相同的 i.
递归
将 i++ 替换为 ++i
main 方法调用 sum 并且必须 return 求和 array.The 程序的目的是在不使用任何循环的情况下找到数组的和。无法检测到错误。
使用递归求数组求和的代码:
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++);
}
}
i++ returns i 在增量之前,所以你用相同的 i.
递归将 i++ 替换为 ++i