How to create a diamond pattern in JavaScript
Overview
In this shot, we will learn how to create a diamond star pattern using JavaScript. This pattern is complex among other patterns. The logic to create a diamond pattern is combining the logic of the upside pyramid and downside pyramid.
A diamond star pattern looks like the image below:
JavaScript code
let n = 5;// Upside pyramidfor (let i = 1; i <= n; i++) {// printing spacesfor (let j = 1; j <= n - i; j++) {process.stdout.write(' ')}// printing starfor (let k = 0; k < 2 * i - 1; k++) {process.stdout.write('*')}console.log();}// downside pyramidfor (let i = 1; i <= n - 1; i++) {// printing spacesfor (let j = 0; j < i; j++) {process.stdout.write(' ');}// printing starfor (let k = (n - i) * 2 - 1; k > 0; k--) {process.stdout.write('*');}console.log();}
Code explanation
- In line 1, we initialize a number that is the
height(rows)of the upside triangle (i.e., 5) and one less than the height of the downside triangle (i.e., 4), so the totalrows(height)for the diamond is9.
Upside pyramid
-
In line 3, we have our outer
forloop, which will iterate over the height of upside triangle (n=5). -
In line 5, we have our first nested
forloop to print spaces forn-itimes, whereiis the outer loop iteration number. Ifi=3, i.e., for the third row, the number of spaces before star is 2, and so on. -
In line 9, we have the second inner
forloop to print*for(2 * i - 1)times, whereiis the current iteration number of the outer loop. Ifi=3, i.e., for the third row, after one space it will print 5 (2 * 3 - 1) star. -
In line 10, the standard method of JavaScript is used to print the space(
*).process.stdout.write()will print the space. -
In line 12, we used
console.log()withnull, as it will change to a new line. We can useprocess.stdout.write(’\n’)to change the line.
Downside pyramid
-
In line 16, we have have our second outer
forloop, which will iterate over one less than the height of the downside pyramid (that is,n-1 = 4 times, heren=5). -
In line 18, our first inner
forloop prints spaces foritimes, whereiis the outer loop iteration number. Ifi=3, i.e., for the third row, the number of space before the star is3, fori=4the space is4, and so on. -
In line 19, the standard method of JavaScript is used to print the space (" ").
process.stdout.write()will print the space. -
In line 22, the second nested
forloop prints*for2 * (n - i) - 1times, whereiis the current iteration number of outer loop. Ifi=3, i.e., for the third row, after 3 spaces it will print3star (2 * (5 - 3) - 1). -
In line 23, the standard method of JavaScript is used to print the space(
*).process.stdout.write()will print the space. -
In line 25, we used
console.log()withnull, as it will change to a new line. We can useprocess.stdout.write(’\n’)to change the line.
Output
We have completed the task to create a diamond star pattern in JavaScript.