Program to print Diamond shape
In this section, you will learn how you can easily print 'diamond shape' and 'pyramid shape' using javascript
Diamond shape program
Let's see, the simple program to create a diamond shape:
➤ Code : Diamond shape program in javascript;
<script>
function diamond(val){
var y, w, shape = '';
for(y = 0; y < val * 2 - 1; y++) {
w = y < val ? y : val * 2 - y - 2;
shape += Array(val - w).join(' ') + Array(w + 1).join('* ') + '*\n';
}
document.write('<pre>' + shape + '</pre>');
// console.log(shape);
}
//Enter your number here, as often as you want to size of diamond.
diamond(5);
<script>
Output :
* * * * * * * * * * * * * * * * * * * * * * * * *
Pyramid shape program
Let's see, the simple program to create a pyramid shape:
➤ Code : Pyramid shape program in javascript;
<script>
function displayPyramid(n) {
for (var i = 0; i<n; i++) {
var str = '';
for (var j = 1; j < n-i; j++) {
str = str + ' ';
}
for (var k = 1; k <= (2*i+1); k++) {
str = str + '*';
}
document.write('<pre>' + str + '</pre>');
// console.log(str);
}
}
// n is the number of lines in your pyramid shape.
displayPyramid(5);
<script>
Output :
* *** ***** ******* *********
Comments