0
Why the output is only 58 not 6 , 48 , 51, 58
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); } }
3 odpowiedzi
+ 3
It's sum of all elements in array.
for loop iterates over all elements and add them with sum variable.
Edit: Can you tell, why do you think it should be 6 ,48 ,51, 58?
+ 1
{
sum += mArr[x]; // it sums all the elements in myArray and store it in sum
}
cout << sum; // gives you total no Store in sum
// gives output 58
But{
sum += myArr[x]:
cout << sum;
}
// it gives you output 6 ,48,51,59
In the first loop we output our some out side the loop
But in second case we put cout inside our loop
So each time loop is running we get an output
+ 1
Because the sum statement is out of for loop and it executes after the for loop i.e the sum of the array