So i was coding a nested loop and came across a problem originally the code was supposed to give a output of "hello" 5 times so i coded it and it gave a output of "hello" six times.
for (i = 0; i < 2; i++) {
for (var j = 0; j < 3; j++) {
console.log("Hello");
}
}
i expected it to give a output of hello 5 times
2
Answers
Your code runs two loops, an outer loop (
i
) that runs twice (fori = 0
andi = 1
), and an inner loop (j
) that runs three times for each iteration of the outer loop (forj = 0
,j = 1
, andj = 2
).Each time the inner loop
runs, it prints "Hello".
Since the inner loop runs three times for each of the two iterations of the outer loop, the total count of "Hello" printed is
2 × 3 = 6
.2 * 3 = 6, skip 1 iteration in the very beginning: