Hello People, here is another interesting script for you!. Usually these kind of programs you could see in C language only, but in our blog I’m writing these pattern program in PHP, JavaScript, Java, Python etc.,
Today’s less is about how to print Diamond pattern in JavaScript!
See the demo here:
See the script here:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<html> <head> <title>JavaScript to print Diamond pattern!</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script> function printDiamond() { document.getElementById("result").innerHTML = ""; var limit = document.getElementById("limit").value; if (limit < 2 || limit > 100) { alert('Please enter value between 1 and 101'); return; } var space = limit; for (i = 1; i <= limit; i++) { for (j = 1; j <= space; j++) { document.getElementById("result").insertAdjacentHTML('beforeend', ' '); } space--; for (j = 1; j <= 2 * i - 1; j++) { document.getElementById("result").insertAdjacentHTML('beforeend', '*'); } document.getElementById("result").insertAdjacentHTML('beforeend', '<br>'); } space = 2; for (i = 1; i <= limit; i++) { for (j = 1; j <= space; j++) { document.getElementById("result").insertAdjacentHTML('beforeend', ' '); } space++; for (j = 1; j <= 2 * (limit - i) - 1; j++) { document.getElementById("result").insertAdjacentHTML('beforeend', '*'); } document.getElementById("result").insertAdjacentHTML('beforeend', '<br>'); } alert('Done!'); } </script> </head> <body> <h2>JavaScript to print Diamond pattern!</h2> Enter the limit: <input type="number" id="limit" min="2" max="100" /> <input type="button" value="Print Diamond Pattern!" onclick="printDiamond()" name="print" /> <br /> <br /> <div id="result"></div> </body> </html> |
Output of the above script will be this:
Enjoy the day!
*
**
***
****
*****
Can you make this pattern in a single loop only? This question is asked in my interview.
var size = 5;
for(i=1; i <= size; i++) {
for(j=1; j<=i; j++) {
process.stdout.write("*");
}
process.stdout.write("\r\n");
}
var x=5;
var str = ‘ ‘;
for(var i=1;i
I used the Absolute function to make it shorter 🙂
//make sure the width is an ODD number to get perfect diamond
var stars=””;
var width = 11;
var num = (width+1)/2;
for (let i = num-1; i >-num; i–) {
for (let j = num-Math.abs(i); j < num; j++) {
stars+=' '
}
for (let j = 0; j < 2*(num-Math.abs(i))-1; j++) { //2*num-(2*Math.abs(i) +1) simplified to 2*(num-Math.abs(i))-1
stars+="*";
}
stars+="\n";
}
console.log(stars);
document.write(“”)
for(i=1; i <= 7; i++) {
for(j=1; j<=i; j++) {
document.write("*");
}
document.write("”);
}
for(i=1; i =i; j–) {
if (j==7)
{
continue
}
document.write(“*”)
}
document.write(“”)
}
document.write(“”)