Search code examples
javascriptfor-loopnumbersnested-loops

JavaScript nested for loops to display numbers without HTML


I need to display a number range between 1 and 30 in the console, but in a specific way. While I've figured out how to get the range using a for loop, I have not figured out how to display the numbers in the console like in the image shown below where each * represents a number 1-30. I need numbers 1-30 to be displayed 7 rows across, and 5 rows down, without using HTML tables.

example

My code, to display the number range, is as follows:

for (var i = 1; i <= 5; i++)
{

    var output = " ";
    for (var j = 0; j <= 7; j += 1)
    {
    output +=  "*" + "\t";
    }

console.log(output);

}

So far I have tried adding a third nested for loop, but there will be 5 iterations of 1 - 30 displayed 7 times. I have also tried using an array of 1-30, a while loop, an if statement, and have tried adding or multiplying variables with similar results.

I can't help but feel like I am approaching this the wrong way. I am considering using an array and having the inner for loop display each index of the array, but I am not sure if JavaScript has the ability to move to the next index after printing the previous index (1 then 2 then 3, etc) in the way in which I need it to as shown in the image.


Solution

  • This code works

    var output="";var count = 0;
    for (var i = 1; i <= 5; i++)
    {
    
        //output = " ";
        for (var j = 0; j < 7; j += 1)
        {
       output +=(count+1)+"\t";count ++;
       }output+="\n";
    
    //document.write(output);
    
    }
    console.log(output);
    

    Output:

    1   2   3   4   5   6   7   
    8   9   10  11  12  13  14  
    15  16  17  18  19  20  21  
    22  23  24  25  26  27  28  
    29  30  31  32  33  34  35
    

    Problem in Question:

    Question States -Number range between 1 and 30 in the console but specified order of matrix is 7*5 which is equal to 35 not 30 which was wrongly mentioned in the questiion.

    Screenshot

    enter image description here