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