There are several patterns problems to solve, but in this shot, we will learn how to print a right triangle star (*
) pattern with help of JavaScript. The right triangle pattern displays *
in the form of a left triangle (right angled from the right side) on the screen or console.
Below is the shape which we will print using *
in the console.
We have to use two for
loops, where one will be a nested for
loop. The outer loop will be for the row (height) of the triangle, and the nested loop will be used for the column.
We will write a program in JavaScript to print a star pattern in the form of a right triangle.
let n = 5;for (let i = 1; i <= n; i++) {// printing spacesfor (let j = 0; j < n - i; j++) {process.stdout.write(' ');}// printing starfor (let k = 0; k < i; k++) {process.stdout.write('*');}console.log();}
In line 1, we initialize a number that is a height of the triangle or the number of rows.
In line 3, we have have our first for
loop, which will iterate over the row (height) of the triangle.
In line 5, we have our first nested for
loop, which will print n - i
spaces.
In line 4, the standard method of JavaScript is used, and process.stdout.write()
will print the spaces.
In line 9, we have our second nested for
loop, which will print i
stars, where i
is the number of times the external loop is executed.
In line 10, the standard method of JavaScript is used, and process.stdout.write()
will print the star (*
).
In line 12, we used console.log()
with null
, as it will change to a new line. We can use process.stdout.write('\n')
to change the line.
We have successfully completed the task to print *
in a form that looks like a right angle triangle. There can be different logics to print the same pattern.