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
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
Share Improve this question asked Apr 2, 2016 at 15:38 YawuarYawuar 591 gold badge2 silver badges8 bronze badges 1-
1
Well, did you declare and initialise
n
andm
anywhere? – Siguza Commented Apr 2, 2016 at 15:40
2 Answers
Reset to default 4You'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++;
}
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>