Yawuar
Yawuar

Reputation: 59

Nested while loops in javascript

I'm trying to make a grid of stars with a nested while loop.

It does work with a for loop:

for(m = 1; m <= 5; m++) {
    for(n = 1;n <= 10; n++) {
        document.write("*" + " ");
    }
    document.write("<br>");
}

but I can't figure out how I can solve it with a while loop:

while(m <= 5) {
    while(n <= 10) {
        document.write("*" + " ");
        n++;
    }
    document.write("<br>");
    m++;
}

Does anyone have any idea?

Thnx

Upvotes: 0

Views: 8579

Answers (2)

Kristian Barrett
Kristian Barrett

Reputation: 3752

The problem is that you do not reset the n variable, so everytime it is 10 and thus not entering the while loop. You need to do:

var m = 0,
    n = 0,
    div = document.getElementById('draw');

function writeToDiv(stringToWrite) {
  div.innerHTML = div.innerHTML + stringToWrite;
}

while (m <= 5) {
  while (n <= 10) {
    writeToDiv("*" + " ");
    n++;
  }
  n = 0;
  writeToDiv("<br>");
  m++;
}
<div id="draw">

</div>

Upvotes: 0

Mattias Buelens
Mattias Buelens

Reputation: 20159

You're missing the initializers. m needs to start and 1, and n needs to restart at 1 every time m is incremented.

var m, n;
m = 1;
while(m <= 5) {
    n = 1;
    while(n <= 10) {
        document.write("*" + " ");
        n++;
    }
    document.write("<br>");
    m++;
}

Upvotes: 4

Related Questions