How to create a left pascal pattern in JavaScript
Overview
In this shot, we’ll learn how to create a Left Pascal star pattern. This pattern has a medium level of complexity.
The image shown below is the Left Pascal star pattern, which we will create using JavaScript.
Code
let n = 5;for (let i = 1; i <= n; i++) {for (let j = 0; j < n - i; j++) {process.stdout.write(" ");}for (let k = 0; k < i; k++) {process.stdout.write("*");}console.log();}for (let i = 1; i <= n - 1; i++) {for (let j = 0; j < i; j++) {process.stdout.write(" ");}for (let k = 0; k < n - i; k++) {process.stdout.write("*");}console.log();}
Explanation
- To draw the upper part of left pascal triangle marked in red, follow the steps below.
-
Line 1: We initialize the number for the triangle’s height or the number of rows.
-
Line 3: This
forloop will iterate forntimes that is 5. So the upper part will have 5 rows. -
Line 4: This first nested
forloop will print spaces before*forn-itimes for the current row(i) of triangle. For example, fori=2spaces for 2nd row will be 3 and fori=3that is for 3rd row spaces before star will be 2 and so on. -
Line 7: This second nested
forloop will print the*foritimes after the spaces, whereiis the outer loop iteration which is current row also so if 1st row number of star is 1, for i=2 numberof start is 2 and so on. -
Line 10: We will change the row using
console.log(), this will change the current line in the console.
-
To draw the lower part of left pascal triangle, marked in blue follow the steps below.
We have already initialized the
nin the upper part. This part will have one less row than the upper part.
-
Line 12: This
forloop will print the lower part of the pattern. It will iterate forn-1times, that is, 5-1 = 4 times. -
Line 13: This nested
forloop is used to print spaces before the stars in a row. The number spaces will be equals to thei(the current iteration or the row for this lower part). So ifi=1that is for the first row of this lower part the spaces will be 1, fori=2that is 2nd row and spaces will be 2 and so on. -
Line 16: In this nested
forloop, it will print the*after the spaces which we print in the aboveforloop, It will print*n-itimes(where n=5, and i is current iteration or the current row). so ifi=1number of*will be5-1(n-i) = 4, fori=2number of*will be5-2(n-i) = 3 and so on. -
Line 19: We will change the row using
console.log(), this will change the current line in the console.
Output
We have created a Left Pascal star pattern in JavaScript.