In this shot, we will learn how to create a hollow diamond star pattern using JavaScript. This pattern is more complex than the simple diamond patterns. Combining the logic of the upside and downside hollow triangle is the simplest way to make a hollow diamond design.
A hollow diamond star pattern looks like the image below:
let n = 5;for (let i = 1; i <= n; i++) {for (let j = n; j > i; j--) {process.stdout.write(' ');}for (let k = 0; k < i * 2 - 1; k++) {if (k === 0 || k === 2 * i - 2) {process.stdout.write('*');}else {process.stdout.write(' ');}}console.log();}for (let i = 1; i <= n - 1; i++) {for (let j = 0; j < i; j++) {process.stdout.write(' ');}for (let k = (n - i) * 2 - 1; k >= 1; k--) {if (k === 1 || k === (n - i) * 2 - 1) {process.stdout.write('*');}else {process.stdout.write(' ');}}console.log();}
for
loop, which will iterate over the height of the upside triangle (which is 5, here n=5
).for
loop, which will print spaces n-i
times. For example, if i=3, then the number of spaces for the third row is 2, for i=4
is 1, and so on.for
loop to print *
at the border of the triangle and the spaces in between.if
condition to check if the iteration is for the border of the diamond, and print *
there.else
condition. If the iteration is for inside the diamond, then it will print spaces.for
loop, which will iterate for one less than the height of the downside triangle (which is n-1
= 4
times, here n=5
).for
loop, which will print spaces i
times. For example, if i=1, then the number of spaces for the first row is 1, for i=4
is 4, and so on.for
loop to print *
at the border of the triangle and spaces in between.if
condition to check if the iteration is for the border of the diamond, and print *
there.else
condition. If the iteration is for inside the diamond, then it will print spaces.We have completed the task to create a hollow diamond star pattern in JavaScript.