Skip to content
Advertisement

JavaScript pyramid

I’m trying to print a pyramid that has odd numbers for edges. For example output should be:
…….5
…3,4,3
1,2,3,2,1
(dots are here just to show formating)

I managed to write:

function p(n){
  let string = "";

for (let i = 1; i <= n; i++) {
 
  for (let j = 1; j <= n - i; j++) {
   string += " " ;
  }
  
  for (let k = 1; k <= 2*i-1; k++) {
    string += n-k +1;
  }
 string += "n";
}
console.log(string);
  
}


p(5);

But I’m not sure how to continue to get wanted result

Advertisement

Answer

You can try it :

function p(n){
  let string = ""
  for (let i = 0; i <= n/2; i++) {
    let k = n - 2 * i
    for (let j =0; j < Math.floor(n/2)*2 + 1; j++) {
      if(j < Math.floor(n/2) - i) {
        string += " ";
      }
      if( j >= Math.floor(n/2) - i && j <= Math.floor(n/2) + i) {
        string += k;
        j < Math.floor(n/2) ? k++ : k--
      }
      if(j > Math.floor(n/2) + i ) {
        string += " ";
      }
    }
    string += "n";
  }
  console.log(string);
}

p(7);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement