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

102
Views
Can't make pyramid of numbers

I Need to get this output:

1

2  3

4  5  6

7  8  9  10

11 12 13 14 15

What I've tried so far:

function getPyramid() {
  let nums = 0;
  for (let i = 1; i <= 15; i++) {
    for (let n = 1; n < i; n++) {
      console.log(n);

    }
    console.log('<br/>');

  }
  return nums;
}
getPyramid();

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

0

Apart from notes given by jnpdx in the comments, I'd add some:

  • for better convention between programmers we tend to name varible nested in for-loop: i, j
  • <br/> for HTML new line, In JS we do \n for that!
  • number++ is same number += 1
  • Conditional_Operator (expression)?true:false instead of if/else
    function getPyramid(Lines) {
    let number = 1; // the counter to display on each line of pyramid!
    for (let i = 1; i <= Lines; i++) {
        let str = '';//line to display
        for (let j = 1; j <= i; j++) {
           str += number++;//incrementing counter
           str += j!=i ? ' ' : ''; //to make space, but not at the end of line.
        }
       console.log(str);//display that line
    }
    }
    getPyramid(5);
about 4 years ago · Juan Pablo Isaza Report

0

    for (let i = 1 ; i <= 5; i++)
    {
      let s = []
      for (let x = i * (i - 1) / 2 + 1; x <= i * (i + 1) / 2; x++)
      { 
        s.push(x)
      }
      console.log(s.join(" "))
    }

about 4 years ago · Juan Pablo Isaza Report

0

It is possible to do with one single loop

function getPyramid() {
  
let nums = 0;
let count = 1; 
let numbers = ''
  for (let i = 0; i <= 15; i++) {
if(count === nums){
     count++
     nums = 0;
     console.log(numbers)
     numbers = ''
 }
 nums ++
 numbers += ' ' + (i +1) 
  }

}
getPyramid();
Or like this you can specify amount of rows..
function getPyramid(rows) {
  
let nums = 0;
let count = 1; 
let numbers = ''
let i = 1
  while (count < rows + 1 ) {
if(count === nums){
     count++
     nums = 0;
     console.log(numbers)
     numbers = ''
 }
 nums ++
 numbers += ' ' + i
 i++;
  }

}
getPyramid(5);

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!