Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

355
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda