0

Why is it necessary to initiate sum=0;

int [ ] myArr = {6, 42, 3, 7}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum);

26th May 2020, 6:37 PM
Harsh Vyas
Harsh Vyas - avatar
3 Respuestas
+ 1
because you cannot say that sum = arr [x] since what I would do is simply save the last value of the array. Variables are not always initialized, although it is a good practice to do it. In your case you want to make a sum of all the elements of the array which if you do it with the uninitialized variable sum × = arr [i] it would throw an exception that will indicate that the variable was not initialized I hope this help you
26th May 2020, 6:48 PM
Emanuel Maliaño
Emanuel Maliaño - avatar
0
Thanks man
26th May 2020, 7:01 PM
Harsh Vyas
Harsh Vyas - avatar