JavaScript Program to Print Inverted Pyramid
Last Updated :
23 Feb, 2024
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.
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.
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
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Using Recursion
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.
Syntax:
function recursiveFunction(parameters) {
// Base case
if (condition);
// recursive
return recursiveFunction(modifiedParameters);
}
// call
recursiveFunction(initialParameters);
Example: To demonstrate printing an Inverted Pyramind in JavaScript using recursion in JavaScript.
Javascript
function recursiveFn(n, tRows) {
if (n <= tRows) {
process.stdout.write( " " .repeat(n - 1));
process.stdout.write( "* " .repeat(2 * (tRows - n) + 1));
console.log();
recursiveFn(n + 1, tRows);
}
}
let r = 5;
recursiveFn(1, r);
|
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Using Array and Join methods
In this approach, we use the Array and Join method to iterate over each row, constructing the strings of leading spaces and the “*” pattern. The resulting string is then pushed into the array and last, the array is joined with the newline character, and the pattern is printed.
Syntax:
let newArray = Array(element1, element2, ..., elementN);
let resultString = array.join(separator);
Example: To demonstrate printing an Inverted Pyramid in JavaScript using Array and the Join method in JavaScript.
Javascript
let r = 5;
let res = [];
for (let i = r; i >= 1; i--) {
let s = Array(r - i + 1).join( " " );
let stars = Array(2 * i - 1).fill( "* " ).join( "" );
res.push(s + stars);
}
console.log(res.join( '\n' ));
|
Output
* * * * * * * * *
* * * * * * *
* * * * *
* * *
*
Share your thoughts in the comments
Please Login to comment...