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:
We have to use two for loops, where one will be a nested for loop. The outer loop will be used for the
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
forloop, which will iterate over the height of the triangle (that is5here). -
In line 4, we have our nested
forloop, which will iterate for less than the current row number. For example,row (n) = 3will execute forj=0,j=1, andj=2. Whenjbecomes equal toi(current row), it will terminate theforloop. -
In line 5, the standard method
process.stdout.write()of JavaScript is used to print the*. The number of times the nestedforloop 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 useprocess.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.