Search code examples
javascriptfor-loopdesign-patternswhile-loopnested-loops

How to print sideways in Javascript?


I want to print a triangl. I am getting my expected result but it's printing in consecutive lines. I want to print the "*" sideways for every for loop's output. How do I do it?

Code:

let a,b,c;
a = 5;
b = 1;
while(b <= a){
  for(c=1;c<=b;c++){
    console.log('*');
  }
  b++;
  console.log('\n')
}

Output

enter image description here


Solution

  • Here's the sample

    let a,b,c;
    let stars ="";
    a = 5;
    b = 1;
    while(b <= a){
      for(c=1;c<=b;c++){
        stars += '*';
      }
      b++;
      stars += '\n';
    }
    console.log(stars)