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); } }

27th Mar 2020, 5:57 AM
Anuj Sharma
Anuj Sharma - avatar
3 ответов
+ 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?
27th Mar 2020, 6:01 AM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 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
27th Mar 2020, 6:19 AM
Saad Saleem
Saad Saleem - avatar
+ 1
Because the sum statement is out of for loop and it executes after the for loop i.e the sum of the array
27th Mar 2020, 2:39 PM
Divyesh patro
Divyesh patro - avatar