I'm trying to calculate the sum of the integers of array whose index belongs to the interval [n1; n2]
n1 & n2 are int & 0 <= n1 <= n2 < array.length
int[] array = new int[] {0, 1, 2, 3, 4, 5, 3};
int zeroToOne = calc(array,0, 1); // Should return 1
int zeroToFive = calc(array,0, 5); // Should return 15
int doubleZero = calc(array,0, 0); // Should return 0
int zeroToSix = calc(array, 0,6); // Should return 18
So I've tried three methods
First method:
public static int calc(int[] array, int n1, int n2) {
int sum = 0;
for (int i = 0; i < array.length; i++){
if (i <= n2 && n1 <= i) {
sum += i;
}
}
return sum;
}
}
I got:
1 15 0 21
Second method:
public static int calc(int[] array, int n1, int n2) {
int sum = 0;
for (int a: array){
if (n1 <= a && a <= n2){
sum += a;
}
}
return sum;
}
I got:
1 18 0 18
Third method:
public static int calc(int[] array, int n1, int n2) {
return Arrays.stream(array, n1, n2).sum();
}
And I got:
0 10 0 15
How can I solve this problem?