0

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

1
  • 1
    Well, did you declare and initialise n and m anywhere? Commented Apr 2, 2016 at 15:40

2 Answers 2

4

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++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I forgot to post the initializers :p But I didn't know that I had to restart n. Thank you very much!
0

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>

1 Comment

No need to reset n twice at both ends of outer loop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.