This article will demonstrate how to create the diamond start pattern in JavaScript.
Possible Diamond Start Patterns:
- Solid Diamond Start Pattern
- Hollow Diamond Star Pattern
- Inverted Hollow Diamond Pattern
Approach to Create Diamond Star Pattern:
- The approach to creating a diamond star pattern will use 2 JavaScript Nested For loops to print the upper and lower half of the diamond.
- We will iterate from 1 to N and back to 1 to cover the diamond structure for input N.
- The nested loop will be used to create the string that contains the row to be printed each time with the condition of diamond that row+column > N and N+row < column.
- Print the resultant string each time using the console.log() method that adds a new line at the end of the output the form the required structure.
Example 1: Solid Diamond Start Pattern
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));
} for (let i = n - 1; i >= 1; i--) {
let str = "*" ;
let space = ' ' ;
console.log(space.repeat((n - i)) + str.repeat(i * 2 - 1));
} |
Output
* *** ***** ******* ********* ******* ***** *** *
Example 2: Hollow Diamond Star Pattern
Javascript
let n = 5; for (let i = 1; i <= n; i++) {
let str = ''
for (let j = 1; j <= 2 * n; ++j) {
if (i + j == n + 1 || (i == j - n + 1)) {
str += '*'
}
else
str += ' '
}
console.log(str);
} for (let i = n - 1; i >= 1; i--) {
let str = ''
for (let j = 1; j <= 2 * n; ++j) {
if (i + j == n + 1 || (i == j - n + 1))
str += '*'
else
str += ' '
}
console.log(str);
} |
Output
* * * * * * * * * * * * * * * *
Example 3: Inverted Hollow Diamond Pattern
Javascript
let n = 5; for (let i = 1; i <= n; i++) {
let str = ''
for (let j = 1; j < 2 * n; ++j) {
if (i + j > n + 1 && (i > j - n + 1))
str += ' ' ;
else
str += '*' ;
}
console.log(str);
} for (let i = n - 1; i >= 1; i--) {
let str = ''
for (let j = 1; j < 2 * n; ++j) {
if (i + j > n + 1 && (i > j - n + 1))
str += ' ' ;
else
str += '*' ;
}
console.log(str);
} |
Output
********* **** **** *** *** ** ** * * ** ** *** *** **** **** *********