+ 1
Waana know how this program execute, full description please.
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); } }
5 Antworten
+ 5
For loop runs till 0 to myArr.length
So first itration
x = 0; sum = 0;
sum+=myArr[x] is same as (sum+=6) so sum = 6
second itration
x = 1; sum = 6;
sum+=myArr[x] is same as (sum+=42) so sum = 48
third itration
x = 2; sum = 48;
sum+=myArr[x] is same as (sum+=3) so sum = 51
forth itration
x = 3; sum = 51;
sum+=myArr[x] is same as (sum+=7) so sum = 58
+ 5
A J Fixed it 😁😅
+ 3
It's very simple as myArr.length = 4 since there are only 4 elements in the array. So x=0 and 0<4 is true and sum+=myArr[x] means sum = sum + myArr[x] but because already sum is 0 we have sum=0+6 since myArr[0] = 6. Similarly the loop iterates and sum value will become 6+42 in the next iteration and so on till it adds all the elements of the array.
+ 3
If you say in simple the length of myArr is 4 and you are using for loop where you are adding each elements. Though length is 4 so it will add 4 times like this:-
sum = sum + myArr[0]; 0 + 6 = 6
sum = sum + myArr[1]; 6 + 42 = 48
sum = sum + myArr[2]; 48 + 3 = 51
sum = sum + myArr[3]; 51 + 7 = 58
So final answer will be 58
+ 2
Sumit Programmer😎😎 Answer will be 58😁