How to display a right triangle pattern in JavaScript
Overview
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.
Code
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();}
Code explanation
-
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
forloop, which will iterate over the row (height) of the triangle. -
In line 5, we have our first nested
forloop, which will printn - ispaces. -
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
forloop, which will printistars, whereiis 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()withnull, 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 a form that looks like a right angle triangle. There can be different logics to print the same pattern.