Where I'm still lagging behind is the for...loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Where I'm still lagging behind is the for...loop?

Somebody please help me explain why the output of the code below outputs 9 var i,j; var c = 0; for(i = 1;i<=3;i++) { for(j=1;j<=2;j++) { c+=j; } } alert(c);

22nd Apr 2019, 4:37 PM
eMBee
eMBee - avatar
3 Answers
+ 6
i runs from 1 to 3 j runs from 1 to 2 c starts at 0 and add the value of j after each iteration i = 1, j = 1 --> c = 1 i = 1, j = 2 --> c = 3 //j = 2, stop this loop, jump back in the outer loop --> i++ i = 2, j = 1 --> c = 4 i = 2, j = 2 --> c = 6 i = 3, j = 1 --> c = 7 i = 3, j = 2 --> c = 9 //i = 3 --> end loop --> c = 9 You should also read the lesson about nested loops.
22nd Apr 2019, 6:05 PM
Denise Roßberg
Denise Roßberg - avatar
+ 5
I seem to understand your answer Denise Roßberg but is there a simpler way to explain it? So I can understand for...loops much better
22nd Apr 2019, 6:27 PM
eMBee
eMBee - avatar
+ 4
Hope this helps: A for loops has three parts: start, end condition, increment/decrement for(int i = 1; i <= 3; i++) i starts at 1 if i > 3 the loop stops i++ --> incement i by 1 It is like a counter: 1, 2, 3 --> stop for(int i = 0; i < 10; i++){ //some code i = 0,1,2,3,4,5,6,7,8,9 --> stop A nested for loop: for(int i = 1; i <= 3; i++){ for(int j = 1; j <= 2; j++){ } } It starts in the outer loop (i = 1) and then jumps in the inner loop: (j = 1, 2 -> stop -> back in the outer loop) i = 2 --> jump in the inner loop: start again --> j = 1,2 --> stop --> jump in outer loop i = 3 --> jump in the inner loop (j = 1,2) --> jump in outer loop i = 3 --> stop --> jump out of the loop
22nd Apr 2019, 6:48 PM
Denise Roßberg
Denise Roßberg - avatar