Here is the code to display pyramid but its not exactly producing required output.
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.
One line of code:
function generatePyramid(n) {
return [...Array(n)]
.forEach((_, i) => console.log([...Array(++i)].map((_, j) => ++j).join(' ')));
}
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();
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)
}