+ 5

I don't understand arrays and loops

please help me

4th Dec 2016, 5:39 PM
Nasim
Nasim - avatar
10 Answers
+ 8
For the line a[j]+=j: This is equivalent to writing a[j] = a[j] + j So when j = 2, a[2] = 5 and so a[2] = 5 + 2 = 7. Hope this helped.
4th Dec 2016, 6:28 PM
Stuart Johnson
Stuart Johnson - avatar
+ 6
var a = [3,8,5]; for(var j = 0;j<3;j++) { a[j]+=j; } document.write(a[2]); Ans=7.But how?
4th Dec 2016, 6:01 PM
Nasim
Nasim - avatar
+ 5
where do u face problem ?
4th Dec 2016, 5:41 PM
Shekhar Bahuguna
Shekhar Bahuguna - avatar
+ 5
how j=2?
4th Dec 2016, 6:42 PM
chandni singh
chandni singh - avatar
+ 5
j= 2 because in an array you start at 0. for example : a[0]=3 a[1]=8 and a[2] = 5. so you do the loop and the last loop is j= 2 and a[j] ==a[2]. so a[j] +=j gives 5+2 --> 7
4th Dec 2016, 11:50 PM
caps
+ 3
before loop executes a[0]=3 a[1]=8 a[2]=5 a[j]+= j; a[j] =a[j] + j j= 0 sum of 0th array element and value if j =0 a[0] = 5 + 0; = 5 sum of a[1] array element and value of j=1 secon time loop: j = 1; a[1] = 8 +1; = 9 sum of a[2] array element and j = 2 third time loop;: j = 2; a[2] = 5 + 2; = 7; loop ends here as loop end of condition j< 3 matches.
4th Dec 2016, 11:47 PM
Shekhar Bahuguna
Shekhar Bahuguna - avatar
+ 3
Thanks all for answer.
5th Dec 2016, 2:50 AM
Nasim
Nasim - avatar
+ 3
Arrey is collection of many values.. and loop is a way to exucute a function many time as u want.
2nd Jan 2017, 1:09 PM
Asif Farooqui
Asif Farooqui - avatar
+ 2
in ur code u got anser 7 becouse u get 2 from your loop and then u add 2 of 3rd value of Array (a) and third value of (a) array is 5 so 5+2=7
2nd Jan 2017, 1:17 PM
Asif Farooqui
Asif Farooqui - avatar
+ 1
Array is used to contain many elements of the same type, so the size can be less and program will be easier to understand. while loop are used for repetition ,. such as if you want to print nos from 1 to 10 , then we have write 10 statements which is not the way of coding , but through loop we can write in simple and coding way: for(i=1;i<=10;i++)
4th Feb 2017, 4:08 PM
Sunnykant Tiwari
Sunnykant Tiwari - avatar