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.

Left pascal star pattern

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 n that is the height of the triangle or number of rows.

  • In line 3, we have our first for loop which will iterate for n times (height of the triangle, that is 5 here).

  • In line 4, in this nested for loop, we print * for i times, where i is the current iteration of the outer loop.

  • In line 7, we change rows using console.log().

  • In line 10, in this nested for loop, we print * for n-i times, where i is the current iteration of the outer loop. For example, if i=2 then 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.

Free Resources