How to print a pyramid pattern using JavaScript
In this answer, we will learn to solve a common coding problem pattern. We will print a star pyramid pattern using JavaScript.
Desired output
We will print the below pattern:
Now let’s explore two different approaches to achieve this result.
Naive approach
We will use the following three for loops:
-
One is the outer loop for rows of the pyramid.
-
The other two are nested loops, where the first inner loop will print the number of spaces (
' ') and the second will print the number of stars (*).
Code
Let’s see the program to create a pyramid pattern:
let n = 5;// External loopfor (let i = 1; i <= n; i++) {// printing spacesfor (let j = 1; j <= n - i; j++) {process.stdout.write(' ')}// printing starsfor (let k = 0; k < 2 * i - 1; k++) {process.stdout.write('*')}console.log();}
Explanation
-
Line 1: We initialize a variable
nwith an integer representing the total number of rows that make up the pyramid. We can also consider this as the height of the pyramid. -
Line 3: We have the first
forloop that will iterate over the total number of rows (5, in the example above). -
Lines 5 to 7: We have the first nested
forloop to print spacesn-itimes, whereiis the current iteration of the outer loop. For example, ifi= 3, we will print 2 spaces in the third row usingprocess.stdout.write(' '). -
Lines 9 to 11: We have the second nested
forloop to print stars2 * i - 1times, whereiis the current iteration of outer loop. For example, ifi= 3, we will print 5 stars in the third row usingprocess.stdout.write('*'). -
Line 12: We used
console.log()withnull, as it will change to a new line. We can also useprocess.stdout.write('\n')to change the line.
Optimise approach
We will use only a single for loop to achieve the desired results:
Use one loop to iterate through each row.
Determine the number of spaces and asterisks for each row using simple calculations.
Utilize string repetition to construct each row efficiently.
Reduce nested loops for better performance and readability.
Code
Let's see the program to create a pyramid pattern:
function printPyramid(rows) {let pyramid = '';// Defined a for loop to iteracte through each rowfor (let i = 0; i < rows; i++) {// Add spaces before the first '*' to center the pyramidpyramid += ' '.repeat(rows - i - 1);// Add '*' for the current rowpyramid += '*'.repeat(2 * i + 1);// Move to the next linepyramid += '\n';}console.log(pyramid);}// Example usage: Print a pyramid with 5 rowsprintPyramid(5);
Explanation
Line 4: We Defined a
forloop to iterate through each row.Line 6: We calculated to add spaces before the first
*to center the pyramid.Line 8: We added
*for that specific role where our for loop is iterating through.Line 10: We brake the line to move over to next line.
Conclusion
We completed the task to print *'s in a form that looks like a pyramid. However, this answer shows both a naive and optimise approach to do it. However, there can be several algorithms to achieve the same result.