JavaScript Program to Print Triangle Star Pattern
Last Updated :
22 Dec, 2023
This article will demonstrate how to create a triangle star pattern in JavaScript. To create the triangle star patterns in javascript, we will use a for loop for the n number of iterations, and in each loop we will print the “*” with the repeat method to increase or decrease the number of stars in each iteration. Also to provide proper space create a whitespace string to give the required space before the stars. Following are the star patterns we are going to discuss:
Upper left triangle
The upper left triangle is a right-angled triangle that has the maximum number of stars at the left side and the bottom. We will use a for loop and repeat() method of string to print this pattern.
Example 1: The below code example contains the code that prints an upper left triangle.
Javascript
let n = 5;
for (let i = 1; i <= n; i++) {
let str = "* " ;
console.log(str.repeat(i));
}
|
Output
*
* *
* * *
* * * *
* * * * *
Upper right triangle
The pattern of this triangle contains the maximum number of start at the right side and the bottom. It is another type of right-angled triangle.
Example 2: The below example explains the logic to print the upper right triangle.
Javascript
let n = 5;
for (let i = 1; i <= n; i++) {
let str = "* " ;
let space = ' ' ;
console.log(space.repeat((n-i))+str.repeat(i));
}
|
Output
*
* *
* * *
* * * *
* * * * *
Lower Right Triangle
The lower right triangle has the maximum number of stars at the top and the right side. It is also an right-angled triangle.
Example 3: The below code example will illustrate the logic to print the ower right triangle star pattern.
Javascript
let n = 5;
for (let i = n; i >= 1; i--) {
let str = "* " ;
let space = ' ' ;
console.log(space.repeat(n-i)+str.repeat(i));
}
|
Output
* * * * *
* * * *
* * *
* *
*
Lower Left Triangle
The lower left triangle has the maximum number of stars at the top and the left side. It is also a type of right-angled triangle.
Example 4: The below code example uses the logi to print the lower left triangle star pattern.
Javascript
let n = 5;
for (let i = n; i >= 1; i--) {
let str = "* " ;
console.log(str.repeat(i));
}
|
Output
* * * * *
* * * *
* * *
* *
*
Share your thoughts in the comments
Please Login to comment...