Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

350
Views
Upside down triangle using one for-loop

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

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

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


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

You can replace all the above

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

with

"#".repeat(i)
about 4 years ago · Juan Pablo Isaza Report

0

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

#####
####
###
##
#
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!