1

I wrote this method that draw a Triangle. For example if you call drawTriangle(5) you get the following output: enter image description here

this is my code :-

function drawTriangle(t){

for (let i=1; i <= t; i++)
{

    for (let j=1; j<=i; j++)
    {
        console.log(j+" ");
    }

    console.log("\n");
}

}
let t = 5 ;
drawTriangle(t);

and i get this output enter image description here

I can not make them in a line I don't Know where is the problem .

  • 3
    Assemble a row as a single string before logging it. Don't do the logging 1 character at a time. – John Coleman Feb 16 '19 at 14:20
  • I second assembling the row first, but I would add that assembling the triangle as rows separated with a newline (`\n`) would be more performant. Additionally, `console.log()` is meant as a debugging tool and shoule be used as such if possible, opting for the function to return the triangle as a string that you then log to the console. – Jordan Stubblefield Feb 21 '19 at 15:57

4 Answers4

2

console.log() will print a new line every time, store each line in a variable and print it at the end of innerLoop

function drawTriangle(t){

  for (let i=1; i <= t; i++)
  {
    let eachLine = ''

      for (let j=1; j<=i; j++)
      {
        eachLine += j + " "
      }
      eachLine = eachLine.trim();
      console.log(eachLine);
  }

}

let t = 5 ;
drawTriangle(t);
yqlim
  • 6,898
  • 3
  • 19
  • 43
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
0

Refer to this. You can use string concatenation in your inner for loop.

Hemang
  • 11
0

Well other answer has already specified what you missed in your code.

I am adding it in case you want to see a alternate solution

let n = 1;
let op = ''

while(n<=5){
  op+=new Array(n).fill(0).map( (e,i) => i+1 ).join(' ') + '\n'
  n++
}

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

Here's a solution with linear time complexity--just console.log(draw(n)), where n is an integer, to see the result:

function draw(n) {
  let triangle = '';
  let prev;
  for (let i = 1; i <= n; i++) {
    if (prev) {
      triangle += '\n';
      prev = prev + ' ' + i;
    } else {
      prev = i;
    }
    triangle += prev;
  }
  return triangle;
}