skip to Main Content

I was using a nested while loop, and ran into a problem, as the inner loop is only run once. To demonstrate I’ve made a bit of test code:

let i = 1, j = 1;
while (i < 5) {
  console.log('outer', i);
  while (j < 4) {
    console.log('inner', j);
    j++;
  }
  i++;
}

Help me how to solve this problem, I have tried in every but the reuslt was the same

5

Answers


  1. Your problem is that you never reset j to 1, after running the inner loop.

    this will reset j to 1 after running the inner loop, and the while loop will now run every time the outer loop runs.

    let i = 1, j = 1;
    
    while (i < 5) {
      console.log('outer', i);
      while (j < 4) {
        console.log('inner', j);
        j++;
      }
      j = 1;
      i++;
    }
    Login or Signup to reply.
  2. Just move the j variable inside the first while loop

    let i = 1
    while (i < 5) {
      let j = 1;
      console.log('outer', i);
      while (j < 4) {
        console.log('inner', j);
        j++;
      }
      i++;
    }
    
    Login or Signup to reply.
  3. Your not reseting the inner counter var.

    let i = 1 , j = 1;
    while(i < 5){
        console.log("outer : " + i);
        while(j < 4){
            console.log("inner : " + j);
            j++;
        }
        i++;
        j = 1; //reset here inner counter after full cicle
    }
    
    Login or Signup to reply.
  4. Could you please put the "j" inside the first loop and try

    let i = 1;
    while(i < 5) {
        console.log('Outer: '+i);
        let j = 1;
        while(j < 4) {
            console.log('Inner: '+j);
            j++;
        }
        i++;
    }
    Login or Signup to reply.
  5. let i = 1;
    while (i < 5) {
      console.log('outer', i);
      let j = 1;
      while (j < 4) {
        console.log('inner', j);
        j++;
      }
      i++;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search