How to use Nested for Loop In Javascript

This approach uses the for loop to print the inverted pyramid by using nested loops we control the spacing and the number of “*” in each row. The outer loop mainly manages the rows and the inner loop controls the leading spaces and printing “*” in the pattern.

Syntax:

for (initialization; condition; iteration) {
for ((initialization; condition; iteration){
//code
}
// code
}

Example: To demonstrate printing an Inverted Pyramid in JavaScript using the Nested for loop in JavaScript.

Javascript




let r = 5;
for (let i = r; i >= 1; i--) {
    for (let j = r - i; j > 0; j--) {
        process.stdout.write("  ");
    }
    for (let k = 0; k < 2 * i - 1; k++) {
        process.stdout.write("* ");
    }
    console.log();
}


Output

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

JavaScript Program to Print Inverted Pyramid

In JavaScript, the Inverted Pyramid is the geometric pattern of “*” that is arranged in the format upside-down. This can be printed using various approaches like Looping, Recursion, and built-in methods.

Table of Content

  • Using Nested for Loop
  • Using Recursion
  • Using Array and Join methods

Similar Reads

Using Nested for Loop

This approach uses the for loop to print the inverted pyramid by using nested loops we control the spacing and the number of “*” in each row. The outer loop mainly manages the rows and the inner loop controls the leading spaces and printing “*” in the pattern....

Using Recursion

...

Using Array and Join methods

In the below approach, we have used the Recursive function which controls the row-wise printing by adjusting the leading spaces and the number of “*” in each row. The base cases make sure that the recursion ends when the “n” exceeds the total rows....

Contact Us