Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Program to Print Triangle Star Pattern

JavaScript Program to Print Triangle Star Pattern

This article will demonstrate how to create a triangle star pattern in JavaScript.

The Possible Triangle Star Patterns are:

  • Upper left triangle
  • Upper right triangle
  • Lower right triangle
  • Lower left triangle

Approach

To create the triangle start 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 starts in each iteration. Also to provide proper space create a whitespace string to give the required space before the stars.

Example 1: Upper Left Triangle.

Javascript




let n = 5;
for (let i = 1; i <= n; i++) {
    let str = "* ";
    console.log(str.repeat(i));
}


Output

* 
* * 
* * * 
* * * * 
* * * * * 

Example 2: 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:

        * 
      * * 
    * * * 
  * * * * 
* * * * * 

Example 3: Lower Right 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:

* * * * * 
  * * * * 
    * * * 
      * * 
        * 

Example 4: Lower Left Star Pattern

Javascript




let n = 5;
for (let i = n; i >= 1; i--) {
    let str = "* ";
    console.log(str.repeat(i));
}


Output

* * * * * 
* * * * 
* * * 
* * 
* 
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments