+ 1
Java - Why This Works?
Hi. Could someone explain to me every part of this code (briefly is fine) and why it works? Thanks! public class Program { public static void main(String[] args) { int [ ] myArr = {19, 45, 23, 64}; int sum=0; for(int x=0; x<myArr.length; x++) { sum += myArr[x]; } System.out.println(sum); } }
4 Answers
+ 5
public class Program
{
public static void main(String[] args) {
// an initialized integer array with 4 elements. myArr.length is 4
int [ ] myArr = {19, 45, 23, 64};
// an integer variable to hold the sum of the array elements
// initialized with zero
int sum=0;
// For loop goes from 0 to 3 which is 4 cycles
for(int x=0; x<myArr.length; x++) {
// first time: sum = 0 + 19; sum = 19
// second time: sum = 19 + 45; sum = 64
// third time: sum = 64 + 23; sum = 87
// forth time: sum = 87 + 64; sum = 151
sum += myArr[x];
}
// print out the sum value to the screen which is 151
System.out.println(sum);
}
}
+ 2
bcz u hv written x <myArr.length
u hv not written x<=myArr.length
u can also use x <=myArr.length -1
+ 1
@babak has it correct.
btw initialized or initialization means to give a variable a value.
0
Here in java array is object of class that is not for our purpose it is developer purpose and it is called factory class. Ok so in that class length variable is there which gives the total length of the array.
Here MyArray.length=4 loop goes 0,1,2,3 {4}times sum =sum+myArr[x]
19+45+23+64 =151 and hence the output is 151