JavaScript Program to Print Hollow Star Pyramid in a Diamond Shape
Last Updated :
08 Mar, 2024
The JavaScript program is designed to print a hollow star pyramid in a diamond shape. This task involves generating a pattern of stars arranged in a pyramid-like shape with hollow spaces in between, forming a diamond silhouette. The program aims to provide a flexible solution that can accommodate different sizes of the diamond, allowing for customization based on specific requirements.
Below are the approaches to print hollow star pyramids in a diamond shape:
Print Hollow Diamond Star Pyramid Using for loop
This approach uses a nested for loop to generate the hollow diamond pattern by iterating through the rows and columns. It uses conditional statements to determine when to print stars and when to print spaces, creating the desired diamond shape.
Example: The below example prints a hollow star pyramid in a diamond shape using for loop in JavaScript.
Javascript
function printHollowStarDiamondNestedLoop(rows) {
for (let i = 1; i <= rows; i++) {
let pattern = "" ;
for (let j = 1; j <= rows - i; j++) {
pattern += " " ;
}
for (let j = 1; j <= 2 * i - 1; j++) {
if (j === 1 || j === 2 * i - 1) {
pattern += "*" ;
} else {
pattern += " " ;
}
}
console.log(pattern);
}
for (let i = rows - 1; i >= 1; i--) {
let pattern = "" ;
for (let j = 1; j <= rows - i; j++) {
pattern += " " ;
}
for (let j = 1; j <= 2 * i - 1; j++) {
if (j === 1 || j === 2 * i - 1) {
pattern += "*" ;
} else {
pattern += " " ;
}
}
console.log(pattern);
}
}
printHollowStarDiamondNestedLoop(5);
|
Output
*
* *
* *
* *
* *
* *
* *
* *
*
Print Hollow Diamond Star Pyramid Using While Loop
This approach employs nested while loops to generate the hollow diamond pattern by iterating through the rows and columns. It uses conditional statements to determine when to print stars and when to print spaces, creating the desired diamond shape.
Example: The below example prints Hollow Star Pyramid in a Diamond Shape using while loop in JavaScript.
Javascript
function printHollowDiamond(n) {
let rows = 1;
while (rows <= n) {
let columns = n;
while (columns > rows) {
process.stdout.write( " " );
columns--;
}
process.stdout.write( "*" );
columns = 1;
while (columns < (rows - 1) * 2) {
process.stdout.write( " " );
columns++;
}
if (rows === 1) {
console.log();
} else {
console.log( "*" );
}
rows++;
}
rows = n - 1;
while (rows >= 1) {
let columns = n;
while (columns > rows) {
process.stdout.write( " " );
columns--;
}
process.stdout.write( "*" );
columns = 1;
while (columns < (rows - 1) * 2) {
process.stdout.write( " " );
columns++;
}
if (rows === 1) {
console.log();
} else {
console.log( "*" );
}
rows--;
}
}
printHollowDiamond(5);
|
Output
*
* *
* *
* *
* *
* *
* *
* *
*
Share your thoughts in the comments
Please Login to comment...