What is the Left Triangle pattern in Javascript?

Overview

In this shot, we will be learning how to print a Left Triangle star (*) Pattern with the help of Javascript. The Left Triangle pattern displays * in the form of the Left triangle, right-angled from the left-side, on the console.

Below is the shape that we will be printing using * in the console:

Left triangle

We have to use two for loops, where one will be a nested for loop. The outer loop will be used for the rowheight of the triangle, and the nested loop will be used for the column.

Code

let n = 5;
for (let i = 1; i <= n; i++) {
for (let j = 0; j < i; j++) {
process.stdout.write("*");
}
console.log();
}

Explanation

  • In line 1, we take a number that is the height of the triangle or number of rows.

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

  • In line 4, we have our nested for loop, which will iterate for less than the current row number. For example, row (n) = 3 will execute for j=0, j=1, and j=2. When j becomes equal to i (current row), it will terminate the for loop.

  • In line 5, the standard method process.stdout.write() of JavaScript is used to print the *. The number of times the nested for loop runs is equal to the number of stars it prints.

  • In line 7, we have used console.log() with null, as it will change to a new line. We can use process.stdout.write('\n') to change the line.

Result

We have successfully completed the task to print * in the form that looks like a Left triangle. This is only one of the many logics that can be used to print the same pattern.

Free Resources