In this case the program is supposed to add all the arrays together. However if I entered 1 in the sum method parameter it would start counting from 7 onwards but if I put 0 it outputs 0.
public class sList {
public static void main(String[]args) {
int[] array = {10,7,11,5,13,8}; // How do I make it read the value 10 as 1 in the array?
sum(array.length,array);
}
public static int sum(int n, int[] S) {
int i;
int result;
result = 0;
for(i=1;i<=n;i++)
result = result + S[i];
System.out.println(result);
return result;
}
}
I wouldn't pass the length in, because:
array.length
tells you the length if you want to know itInstead, just iterate through the whole array passed in using a foreach loop:
public static int sum(int[] array) {
int result = 0;
for (int i : array)
result += i;
return result;
}
Doing this results in a lot less code, which in turn is easier to read and understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With