Skip to content Skip to sidebar Skip to footer

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('*'

Solution 1:

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++;
}

Solution 2:

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>

Post a Comment for "Nested While Loops In Javascript"