How do I print a pyramid pattern in JavaScript?

IT Training
2 min readNov 27, 2023

--

To print a pyramid pattern in JavaScript, you can use nested loops. Here’s a simple example of how you can achieve this:

javascript

Copy code

function printPyramid(height) {

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

let row = ‘’;

// Add spaces before the stars

for (let j = 1; j <= height — i; j++) {

row += ‘ ‘;

}

// Add stars

for (let k = 1; k <= 2 * i — 1; k++) {

row += ‘*’;

}

console.log(row);

}

}

// Example: Print a pyramid with height 5

printPyramid(5);

This example defines a function printPyramid that takes the height of the pyramid as an argument and uses nested loops to construct each row of the pyramid. The outer loop (i) iterates over the rows, and the inner loops (j and k) are used to add spaces and stars to each row.

You can call the function with different height values to print pyramids of varying sizes. Adjust the loop conditions and patterns as needed based on your requirements.

it course in Chennai, it institute in Chennai, it training center in Chennai, best it courses in Chennai, software courses in Chennai, software training institutes in Chennai

--

--

IT Training
0 Followers

We provide IT Training at lowest cost.