Home > database >  Upside down triangle using one for-loop
Upside down triangle using one for-loop

Time:11-17

I am trying to print an upside down right-angled triangle using one for-loop, without the "\n" in Javascript. This is my code:

function triangle(num) {
  triangleStr = "";
  for (let i = num; i > 0; i--) 
  {
    triangleStr  = "#";
    console.log(triangleStr);
  }
}
triangle(5);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

1) You can create a upside down right angled triangle as:

triangleStr = Array(i).fill("#").join("");

function triangle(num) {
  triangleStr = "";
  for (let i = num; i > 0; i--) {
    triangleStr = Array(i).fill("#").join("");
    console.log(triangleStr);
  }
}
triangle(5);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

2) You can also achieve the result using recursion as:

function triangle(num) {
  if (num === 0) return;
  console.log(Array(num).fill("#").join(""));
  triangle(num - 1);
}
triangle(5);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

3) Just using recursion

function triangle(start, end) {
  if (start > end) return;
  triangle(start   1, end);
  console.log(Array(start).fill("#").join(""));
}
triangle(1, 5);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>


Edited: Thanks to TAHERElMehdi who suggested this solution using repeat as:

You can replace all the above

Array(i).fill("#").join("");

with

"#".repeat(i)

CodePudding user response:

Your code is fine, Just get rid of triangleStr and replace it inside for-loop with method repeat.

function triangle(num) {
  for (let i = num; i > 0; i--) 
  {
    console.log("#".repeat(i));
  }
}
triangle(5);

Result

#####
####
###
##
#
  • Related