In this article, we will demonstrate how to create pyramid star patterns in JavaScript.
The Possible Pyramid Star Patterns are:
- Upper pyramid
- Inverted pyramid
- Left inverted pyramid
- Right inverted pyramid
Approach
There will be two different approaches based on alignments i.e. horizontal and vertical.
Horizontally Inverted Pyramid
- This type includes the upper pyramid and the inverted pyramid.
- To achieve this we will use a javascript for loop to iterate N time
- In that loop, print spaces repeat N-1 times before and after the start.
- As the number of start changes by 2 in every line repeat the stars 2*i -1 times to get the required structure.
Vertically Inverted Pyramid
- Vertically inverted pyramids include the Rigth inverted and Left inverted pyramids
- To achieve this we will use Javascript for loop 2 time i.e. from 1 to N and back to 1.
- In that loop, print spaces repeat N-i times before and after the start.
- As the number of start changes by 1 in every line repeat the stars i times to get the required structure.
Example 1: Upper pyramid
Javascript
let n = 5; for (let i = 1; i <= n; i++) { let str = "* " ; let space = ' ' ; console.log(space.repeat((n - i)) + str.repeat(i * 2 - 1)); } |
* * * * * * * * * * * * * * * * * * * * * * * * *
Example 2: Inverted pyramid
Javascript
let n = 5; for (let i = n; i >= 1; i--) { let str = "* " ; let space = ' ' ; console.log(space.repeat((n - i)) + str.repeat(i * 2 - 1)); } |
* * * * * * * * * * * * * * * * * * * * * * * * *
Example 3: Left inverted pyramid
Javascript
let n = 5; for (let i = 1; i <= n; i++) { let str = "* " ; let space = ' ' ; console.log(space.repeat((n - i)) + str.repeat(i)); } for (let i = n - 1; i >= 1; i--) { let str = "* " ; let space = ' ' ; console.log(space.repeat(n - i) + str.repeat(i)); } |
* * * * * * * * * * * * * * * * * * * * * * * * *
Example 4: Right inverted pyramid
Javascript
let n = 5; for (let i = 1; i <= n; i++) { let str = "* " ; console.log(str.repeat(i)); } for (let i = n - 1; i >= 1; i--) { let str = "* " ; console.log(str.repeat(i)); } |
* * * * * * * * * * * * * * * * * * * * * * * * *