Home > Back-end >  I am trying to use a for loop in javascript to create a a table that displays * and for each row the
I am trying to use a for loop in javascript to create a a table that displays * and for each row the

Time:11-11

***let numRows = 5;
let numColumns = 10;
let strRowOutput = "";
for (let row = 1; row <= numRows; row  ) {
    for (let column = 1; column <= numColumns; column  ) {
        strRowOutput  = "*";
    }
    console.log(strRowOutput);
    strRowOutput = "";
}
console.log();***

thats the code so far but it only displays the last row with 10*.enter image description here

CodePudding user response:

The second for loop condition should be dependent to the variable in first for loop like column <= row OR if you want to restrict the column to a maximum value, you can use column <= Math.min(row, numColumns)

Im using the second approach here

Working fiddle

let numRows = 5;
let numColumns = 10;
let strRowOutput = "";
for (let row = 1; row <= numRows; row  ) {
  for (let column = 1; column <= Math.min(row, numColumns); column  ) {
      strRowOutput  = "*";
  }
  console.log(strRowOutput);
  strRowOutput = "";
}
console.log();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related