How to create a right pascal pattern in Javascript
Overview
In this shot, we will learn how to create a right pascal star pattern. It is easier than the left pascal logic.
The image shown below is the left pascal star pattern which we will create using Javascript.
Code
Let’s write a Javascript code to create a right pascal star pattern.
let n = 5;for (let i = 1; i <= n; i++) {for (let j = 0; j < i; j++) {process.stdout.write("*");}console.log();}for (let i = 1; i <= n - 1; i++) {for (let j = 0; j < n - i; j++) {process.stdout.write("*");}console.log();}
Explanation
-
In line 1, we initialize a number
nthat is the height of the triangle or number of rows. -
In line 3, we have our first
forloop which will iterate forntimes (height of the triangle, that is 5 here). -
In line 4, in this nested
forloop, we print*foritimes, whereiis the current iteration of the outer loop. -
In line 7, we change rows using
console.log(). -
In line 10, in this nested
forloop, we print*forn-itimes, whereiis the current iteration of the outer loop. For example, ifi=2then the number of times the star will be printed is 5 - 2 = 3 in the second row.
Output
We have successfully printed the right pascal pattern in the console.