8

Here is the code to display pyramid but its not exactly producing required output.

function generatePyramid() {
  var totalNumberofRows = 5;
  var arr = new Array();
  for (var i = 1; i <= totalNumberofRows; i++) {
    for (var j = 1; j <= i; j++) {
      arr.push(j);
      console.log(j);
    }
    console.log("\n");
  }
}

Required Output

2
  • so what is the required output? Commented Dec 23, 2013 at 7:39
  • 1
    the image is the required output how can i show in this format? Commented Dec 23, 2013 at 7:39

34 Answers 34

18

Try the below code

function generatePyramid() {
    var totalNumberofRows = 5;
    var output = '';
    for (var i = 1; i <= totalNumberofRows; i++) {
        for (var j = 1; j <= i; j++) {
            output += j + '  ';
        }
        console.log(output);
        output = '';
    }
}

generatePyramid();
   

Sign up to request clarification or add additional context in comments.

Comments

14

The easiest solution is:-

function pyramid(n) {

 

  for(let i=1; i<= n; i++){

    let str = ' '.repeat(n-i);

    let str2 = '*'. repeat(i*2 -1)

 

    console.log(str + str2 + str);

  }

}

pyramid(5);

Comments

11

This will create a proper pyramid in a console:

function createPyramid(rows)
{
    for (let i = 0; i < rows; i++) {
        var output = '';
        for (let j =0; j < rows - i; j++) output += ' ';
        for (let k = 0; k <= i; k++) output += '* ';
        console.log(output);  
    } 
}

createPyramid(5) // pass number as row of pyramid you want.

Comments

7

This could be done using a single for loop.

var num = "";
var size = prompt("Enter the size of the pyramid");
for(var i=1; i<=size; i++)
{
  num = num + i
  console.log(num);
}

2 Comments

pyramid is not suppose to be a right angle triangle.
I guess neither I nor the person who has asked the question is too concerned about the what a pyramid is and how it looks.
7

**You can FRAME for loop conditions for any patterns given either it may be a triangle, right-angled triangle, inverse triangle, etc.. For more info refer the below code and workbook image. PS: in work book image in step 6 it is 2 + i and not 3+i therefore j >= 4 - i && j <= 2 + i for any number of rows n formula is : j >= n+1 - i && j <= n - 1 + i **

EDIT: In Work book image in step 6 it is 2+i and not 3+i therefore j >=4 - i && j <=2 +i for any no. of rows 'n' formula is j > = n + 1 - i && j < = n - 1 + i

1, 3, 5, 7, 9 => Odd number series (stars) appear in pyramid pattern
1, 2, 3, 4, 5 => Counter (number of rows)

For each counter there exist (2 * n) - 1 value

    function pyramid(n) {  // Input or number of rows
        for (var i = 1; i <= n; i++) {
            var s = "";
            // For every each counter there exist 2*n-1 value
            for (var j = 1; j <= (2 * n - 1); j++) {
              // Hint: Check the workbook image
                (j >= n + 1 - i && j <= n - 1 + i) ? s += "*" : s += " ";   
            }
            console.log(s);
        }
    }
    pyramid(5);

enter image description here

For your requirements, the following code should be fine:

    function generateNumberTriangle(v) {
    for (var i = 1; i <= v; i++) {
        var chars = " ";
        for (var j = 1; j <= v; j++) {
            if (j <= i) { chars += j + "  "; }
        }
        console.log(chars);
    }
}
generateNumberTriangle(7);

Comments

5

You should generate an array on every row iteration and output it at the end:

function generatePyramid() {
    var totalNumberofRows = 5,
        arr;
    for (var i = 1; i <= totalNumberofRows; i++) {
        arr = [];
        for (var j = 1; j <= i; j++) {
            arr.push(j);            
        }
        console.log(arr.join(" ") + "\n");
    }
}

Comments

3

A fun little solution :)

//set the value of n here      
var n = 5;
generateNumberTriangle(n);

function generateNumberTriangle(n) {
    var width = (2 * n) -1; // Always the case.
    var midpoint = Math.floor(width / 2); // Middle of pyramid.
    let level = ''; // will be reset each level loop

    for(var i = 0; i < n; i++) { // Looping through levels
        level = '';
        for(var j = 0; j < width; j++) {
            if(j < midpoint-i || j > midpoint+i) {
                level += '.';
            } else {
                level += '#';
            }
        }
        console.log(level);
    }
}

Comments

3

One of the Easiest solution is using the .repeat function

let count = 1;
let x = "# ";
for (a = 0; a<=5; a +=1){
    console.log(x.repeat(count));
    count +=1;
}

Comments

2

Why not this ?

let printPyramid = (n) => {
    if (n===0) {
        return false;
    } else {
        let arr = [];
        for(let i=0; i<n; i++) {
           arr.push(i);
           console.log(arr.toString());
        }
    }
}

Comments

2

Here's a simple solution using ES6 syntax

function generatePyramid(num) {
  let number = '';

  for (let i = 1; i <= num; i++) {
    console.log(number += i);
  }
}
generatePyramid(5);

3 Comments

I don't think that'll display as a pyramid, it'll pretty much just display the same thing as the OP put in their question, which is not the desired outcome.
When executed in console: 1 12 123 1234 12345 Is this not what the problem asked for?
No, that's a triangle, not a pyramid. That produces the output they're already getting, but not what they need.
2

Another Option

One line of code:

function generatePyramid(n) {
    return [...Array(n)]
        .forEach((_, i) => console.log([...Array(++i)].map((_, j) => ++j).join(' ')));
}

Comments

1
function generatePyramid(num) {
  for (var i = 1; i <= num; i++) {
    var arr = [];
    for (var j = 1; j <= i; j++) {
      arr.push(j);
    }
    console.log(arr);
  }
}

Comments

1
  const pyramid = (n)=>{
  const mid = Math.floor((2*n-1)/2);
  for(let row=0; row<n; ++row)
  {
    //for each row, make empty steps
    let level = ''
    for(let col=0; col<2*n-1; col++)
    {
      if(mid-row <=col && mid+row >= col)
        level+='#';
      else level +=' ';
    }
    console.log(level);
  }
}
pyramid(3);

Comments

1

Simple code of Number Pyramid

for(var i=1; i<=5; i++){
 var Num='';
 for(var j=0; j<i; j++){
     Num += i;
 }
 print(Num) }

Comments

1

To draw a pyramid on the console using JavaScript

  1. Make each line have an odd number of fill characters.
  2. Prepend spaces (or 'spacer characters') before each line, excluding the last.
    To do this:
    • Use repeat() to determine the number of spacer characters for each line. You do that by passing the number of lines - 1 as an argument.

Here's my solution

function drawPyramid(lines, fillChar, spacerChar) {
  let fillChars = '';
  let spacer = spacerChar || ' '; // Default spacer is ' '
  let spacerCount = lines;

  for (let i = 1; i <= lines; i++) {
      fillChars += fillChar;

  // Makes lines always have an odd number of fill characters
    if (i >= 2)
        fillChars = fillChar + fillChars;

    console.log(spacer.repeat(spacerCount - 1) + fillChars);
    spacerCount--;
  }
}

drawPyramid(4, '*');

Comments

1
  function pyramid(){
        var lines = 5;
        var triangle = "";
        for(var i = 0; i < lines; i++){
            for(var j = i; j < lines; j++) {
                triangle += " "
            }
            for(var j = 0; j <= i; j++) {
                triangle += "X "
            }
            triangle += "<br>"
        }
        console.log(triangle)
    }

1 Comment

With so many other answers already posted, you need to explain how/why yours is different from or better than those older solutions.
0
function pyramid() {
    var n = 5;
    var output="";
    for (var i = 0; i <n; i++) {
    var myspace = "";   
    for(let s = 0; s <(n-i-1); s++) {
        myspace += " ";
    }
        for (var j = 1; j <= 2*i + 1; j++) {
            output+="*";

        }
        console.log(myspace+output);
        output="";
    }
}

Output

            *
VM74:11    ***
VM74:11   *****
VM74:11  *******
VM74:11 ********* 

Comments

0

I would stick to recursive approach in such a case:

function generatePyramid (n, row = 0, line = '', number = 1) {
  
    if(row === n){
      return;
    }
    
    if (line.length === n) {
        console.log(line )
        return generatePyramid (n, row + 1)
    } 
    
    if (line.length <= row) {
        line += number;
    } else {
        line += ' ';
    }
    
    generatePyramid (n, row, line, number + 1)
  }

Comments

0

Assuming you want to return numbers and not asterisks as the other answers show, here is that solution:

Note that this solution runs in linear (O(n)) time complexity and doesn't sacrifice performance by logging every line to the console, but the entire pyramid at once instead.

function generatePyramid(n) {
  let pyramid = '';
  let prev;

  for (let i = 1; i <= n; i++) {
    if (prev) {
      pyramid += '\n';
      prev =  prev + ' ' + i;
    } else {
      prev = i;
    }
    pyramid += ' '.repeat(n - i) + prev;
  }

  return pyramid;
}

Log to the console as such: console.log(generatePyramid(n));

If you're looking to just draw a triangle as the picture in your question shows, this function will do that (again, in linear time complexity):

function drawTriangle(n) {
  let triangle = '';
  let prev;
  for (let i = 1; i <= n; i++) {
    if (prev) {
      triangle += '\n';
      prev = prev + ' ' + i;
    } else {
      prev = i;
    }
    triangle += prev;
  }
  return triangle;
}

Comments

0

Shorter way

 function generatePyramid(n) {
        var output="";
        for (var i = 1; i <= n; i++) {
            output += i + " ";
            console.log(output);
        }
    }  

    generatePyramid(5);

Comments

0

If we're talking about the 'pyramid' problem, then this would be an appropriate solution.

function pyramid(n) { // If (e.g.) n=3;
  const columnLength = (n * 2) - 1; // 5 
  let middle = Math.floor(columnLength / 2) // middle would be 2
  for(let row=0; row<n; row++) { // let's create the rows (row = horizontal)
    let res = ''; // init our output inside of the 1st for loop
    for(let col=0; col<columnLength; col++) { // creating the columns (column = vertical)
// The following formula would yield the result we need: 
// (n * 2) - 1 => row=2;col=3; row=3;col=5; row=5;col=9
// We got 2 sides, right? 
// So, before we insert '#' we need to make sure the following logic is met:
// Look at:  (middle - row) as being the left side and  (middle + row) as the right one.
// Only if both conditions are met, we want to insert the "#" sign
      if(middle - row <= col && middle + row >= col ) {
         res += '#';
      } else {
// If '#' is NOT inserted then we want to insert something else, right?! 
// In our case that would be an empty string
        res += ' ';
      }
    }
    console.log(res);
  }
}

pyramid(3);


And if we want to be extra 'fancy, we coučld implement recursion:

function recursiveP(n, row=0, res='') { // IMPORTANT: Pass some default values
      const columnLength = (n * 2) - 1;
      let middle = Math.floor(columnLength / 2);
      // This is our EXIT condition, meaning, if have the n number of rows, our work is done!!
      if(n === row) {
        return;
      }
      //  *** Moving on ***
      //   Initially, this will be skipped, and we'll go to the next check and add the appropriate character,
      //   however, after we're finished w/ creating the 1st row we'll hit this check, we'll print the previously generated result,
      //   and call the function again, but this time incrementing the ROW value. This will continue until the 1st check is met
      if(res.length === columnLength) {
         console.log(res);
         return recursiveP(n, row + 1);
      }
      //   Here we're creating the columns and in each, we're inserting the appropriate char
      if(middle - row <= res.length && middle + row >= res.length ) {
         res += '#';
      } else {
         res += ' ';
      }
      //Initial [recursive] function call
      recursiveP(n, row, res);
    }
    
    recursiveP(6);

Comments

0

If you want to print out a right angle triangle using symbols or single digits. You can use the following code.

let pyramid = '';
for(pyramid.length=0; pyramid.length<=7 ; pyramid+='#'){
  console.log(pyramid);
}

Comments

0

function pyramid(n){ const midpoint = Math.floor((2 * n-1)/2);

for(let row = 0 ; row < n ; row ++){ let level = '';

 for(let column = 0 ; column < 2*n-1 ; column++)
    {
     if(midpoint-row <= column && midpoint + row >= 
        column){
        level += '#';
       }
       else{
           level += ' ';
           }

    }
   console.log(level);
  }

}

pyramid(5);

Comments

0

So many inspiring answers; I like to add mine :)

    let m, o, r, c, pr = (n, x = (n << 1) - 1) => {
        m = (x >> 1) << 0;
        o = '';
        for (r = 0; r < n; r++) {
            for (c = 0; c < x; c++)
                o += (m - r <= c && m + r >= c) ? "#" : " ";
            o += '\n';
        }
        console.log(o);
    }

    pr(5);
    pr(20);
    pr(2);

Comments

0

my solution.

function pyramid(n) {
// generate base of pyramid, aka longest possible string
let limit = n+n-1;

let hashesToPrint = 1; // number of hashes to print
for (let i=0; i<n; i++) {
    
    // get length of spaces we need on each side
    let difference = (limit - hashesToPrint) / 2;
    
    // generate spaces string
    let spaces = ' '.repeat(difference);

    // create pounds string
    let pounds = '#'.repeat(hashesToPrint);

    // append spaces on either side of our pound string
    let newString = spaces + pounds + spaces

    console.log(newString)

    // increment our counter by two
    hashesToPrint += 2
}

}

pyramid(3)

Comments

0

function pyramid(row){
    for(var i = 0; i <=row; i++){
        var space="";
        for(let s = 0; s<=(row-i-1); s++){
            space= space+" ";
        }
        var result="";
        for (var j = 1; j <=2*i+1; j++ ){
            result= result+"*"; //result=result+*
        }
        console.log(space+result);
          result="";
    }
   return result;
}
console.log(pyramid(5));

Comments

0
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pyramid triangle star pattern - javascript</title>
</head>
<body>
  <h2>Pyramid triangle star pattern in javascript</h2>
  <script>
    let n = 5;

    // External loop
    for (let i = 1; i <= n; i++) {
      // printing spaces
      for (let j = n; j > i; j--) {
        document.write('&nbsp;')
      }
      // printing star
      for (let k = 0; k < i * 2 - 1; k++) {
       document.write("*")
      }
    document.write("<br/>")
    }

  </script>
</body>
</html>```

1 Comment

suggestion : you can simply show the javascript without the unneccesary html codes
0

function pyramid(n) {
  for (let i = 2; i < n + 2; i++) {
    console.log(" ".repeat(n + 2 - i) + "*".repeat((i - 2) + (i - 1)));
  }
};

pyramid(10);

This is another solution, taking leverage of Fibonacci sequence: 1,3,5,8,13 etc.

Comments

0
function printNumbers(rows){
  for(let i=1;i<=rows; i++){
   let str='';
   for(let j=1;j<=i; j++){
    str = str + j+' ';
   }
   console.log(str);
  } 
}
printNumbers(5);

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

The most easiest way is:

let ans = [], temp="", n=4;

for (let i=0; i<n; i++) {
  temp += "* ";
  ans.push(temp);
  console.log(temp)
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.