Search code examples
javascriptwhile-loopnested-loops

Question about nested while loop rectangle


I am working on drawing a rectangle using Javascript. Unfortunately, it appears that the outer loop of my nested while isn't working properly. Currently (xy) appears five times on one line and it does not repeat on concurrent lines as expected.

    function Art() { 
// row and col are taking input data from the form in index
    //var row = document.getElementById("row").value; 
    //var col = document.getElementById("height").value; 
    var row=5; 
    var col=3;

    var countrow =1; 
    var countcol =1; 
   document.getElementById("magic").innerHTML=("rectangle has "+ row +" rows and "+ col + " columns");

      while (col> countcol){

           while(countrow<=row){ 
            document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
            countrow++;
           } 
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
        countcol++; 
    }


}

Current output for one run: (xy)(xy)(xy)(xy)(xy)

Could someone have a look at my code and help me understand my logic error?

Thank you.

Expected output


Solution

  • Your loop variable countrow goes to the value of row the first time, but then in the next iteration of the outer while loop it does not restart. So then the inner while will no longer execute.

    Also, your loops seem to be positioned in the wrong order: you should first iterate the rows, and then per row iterate the columns.

    Fix it by swapping the loops and resetting the inner loop counter in each iteration:

    var countrow = 1;
    while(countrow<=row){ 
        countcol = 1;
        while (countcol<=col){
            document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
            countcol++;
        } 
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
        countrow++; 
    }
    

    It would be better if you would use a standard for loop for this (instead of while):

    for (let countrow = 0; countrow < row; countrow++){
        for (let countcol = 0; countcol < col; countcol++){
            document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"(XY)";
        } 
        document.getElementById('count').innerHTML=document.getElementById('count').innerHTML+"<p></p>"; 
    }
    

    That will at least make it work. I should however add that repeatedly adding content to innerHTML is not really best practice.

    Here is how it can also be done, with just one assignment to innerHTML:

    document.getElementById('count').innerHTML=
        Array.from({length: row}, () => "(XY)".repeat(col)).join("<p></p>");