skip to Main Content

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


  1. Your code runs two loops, an outer loop (i) that runs twice (for i = 0 and i = 1), and an inner loop (j) that runs three times for each iteration of the outer loop (for j = 0, j = 1, and j = 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.

    Login or Signup to reply.
  2. 2 * 3 = 6, skip 1 iteration in the very beginning:

    for (i = 0; i < 2; i++) {
        for (var j = 0; j < 3; j++) {
            !i && !j || console.log("Hello");
        }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search