In this answer, we will learn to solve a common coding problem pattern. We will print a star pyramid pattern using JavaScript.
We will print the below pattern:
Now let’s explore two different approaches to achieve this result.
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 (*
).
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();}
Line 1: We initialize a variable n
with 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 for
loop that will iterate over the total number of rows (5, in the example above).
Lines 5 to 7: We have the first nested for
loop to print spaces n-i
times, where i
is the current iteration of the outer loop. For example, if i
= 3, we will print 2 spaces in the third row using process.stdout.write(' ')
.
Lines 9 to 11: We have the second nested for
loop to print stars 2 * i - 1
times, where i
is the current iteration of outer loop. For example, if i
= 3, we will print 5 stars in the third row using process.stdout.write('*')
.
Line 12: We used console.log()
with null
, as it will change to a new line. We can also use process.stdout.write('\n')
to change the line.
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.
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);
Line 4: We Defined a for
loop 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.
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.