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 .

2
  • 3
    Assemble a row as a single string before logging it. Don't do the logging 1 character at a time. Commented Feb 16, 2019 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. Commented Feb 21, 2019 at 15:57

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

3 Comments

your are missing the line-break
@ToniMichelCaubet Is it needed? console.log() will add it implicitely
I actually missread the question. If it's about just console logging.. right, you don't need it
0

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

Comments

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)

Comments

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;
}

Comments