0

How does this work

int myArr[5]; for(int x=0; x<5; x++) { myArr[x] = 42; } I don't understand this, please explain.

18th Jan 2020, 9:01 PM
Enderman Robot
Enderman Robot - avatar
4 Respuestas
+ 2
The loop stores the number 42 in location myArr[x] each time the loop runs. So when x is 0, at the location myArr[0] the number 42 is stored. Then x gets incremeted by 1 which makes x=1. So now at the location myArr[1] the number 42 is stored, etc. This keeps happening until x becomes 5 which then the loop stops.
18th Jan 2020, 9:35 PM
Manoah
Manoah - avatar
+ 1
So they are all 42? myarr[0] is 42, myarr[1] is 42 etc?
18th Jan 2020, 10:05 PM
Enderman Robot
Enderman Robot - avatar
+ 1
Yes theyll all be 42
18th Jan 2020, 10:26 PM
Manoah
Manoah - avatar
0
Well you have declared an array of size 5. Then '"for" loop indicating the index of the array starting from 0 and ending at x<5= 4. Initially when loop will run so x will be 0 and it will put 42 as a first element in array at 0 index then in next iteration due to increment value of x will be 1 and it will place 42 at 1's index of array and so on.... You just consider your loop is handling index of the array and it is putting value 42 at each index of array. 😊
19th Jan 2020, 3:22 AM
Muhammad Umais
Muhammad Umais - avatar