0
I don't understand why the code use x in sum+=myArr[x]. I have tried to use double instead int and it doesn't work.
public class Program { public static void main(String[] args) { int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }
2 Answers
+ 2
X is used because you are using a loop. during first loop x will be 0, so element of index 0 of myArr(which is 6) will be added to sum. Then loop will run again and x will be incremented by one, so it will be 1 and element of index 1 of myArr(which is 42) will be added to sum. And so on untill loop reaches the end. Also you have to use only int values for indexing. Indexs can not be decimals.
+ 1
aaaaah! okay thank you