Open In App

JavaScript Program to Print 180 Rotation of Simple Pyramid

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

A program to print 180 rotations of a simple pyramid involves iterating through a loop 180 times, each time printing the pyramid with a different orientation. This is achieved by adjusting the number of spaces and asterisks printed in each row to create the desired pyramid shape.

There are several ways to achieve this using JavaScript which are as follows:

Using Nested Loop

Nested looping involves using one loop inside another. In this program, the outer loop controls the rows of the pyramid, while the inner loop determines the number of asterisks printed in each row, resulting in the desired pyramid shape.

Example: In this example, The function myFunction prints a pyramid with rows of rows using nested loops. The outer loop controls the rows, and the inner loop determines the number of asterisks in each row, resulting in a pyramid shape.

Javascript




function myFunction(rows) {
    for (let i = 1; i <= rows; i++) {
        let pattern = "";
        for (let j = 1; j <= rows - i; j++) {
            pattern += " ";
        }
        for (let k = 1; k <= i; k++) {
            pattern += "*";
        }
        console.log(pattern);
    }
}
 
myFunction(3);


Output

  *
 **
***

Rotate Using Array

Using an array and join, this approach pre-generates a pyramid pattern into an array. Then, it rotates the pyramid 180 times by accessing array elements modulo the size of the pyramid, printing each row in sequence to achieve the desired rotation effect.

Example: In this example The function prints a symmetrical equilateral triangle pyramid with 5 rows. Each row consists of spaces, asterisks (increasing by 2 each row), and trailing spaces, creating the triangular shape.

Javascript




function myFunction() {
    const size = 3; // Adjust the size as per your requirement
    for (let i = 1; i <= size; i++) {
        console.log(' '.repeat(size - i) + '*'.repeat(i));
    }
}
 
myFunction();


Output

  *
 **
***


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads