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

6th Nov 2019, 3:11 AM
Minhaj Haider
Minhaj Haider - avatar
5 ответов
+ 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
6th Nov 2019, 5:22 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 5
A J Fixed it 😁😅
6th Nov 2019, 5:26 AM
Sumit Programmer😎😎
Sumit Programmer😎😎 - avatar
+ 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.
6th Nov 2019, 3:33 AM
Avinesh
Avinesh - avatar
+ 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
6th Nov 2019, 5:22 AM
A͢J
A͢J - avatar
+ 2
Sumit Programmer😎😎 Answer will be 58😁
6th Nov 2019, 5:24 AM
A͢J
A͢J - avatar