Reputation:
I'm trying to create a program that generates a a pyramid of stars. The amount of layers the pyramid has are dependent on the user's input. For example, if the user entered a 2, it would display something like
*
***
^As you can see, it adds two stars per layer and the number of layers is too. I've already made the basic code for this. I have figured out how to make the layers, but I can't seem to figure out how to get the number of layers right. I figured out of how get 2 stars to appear on each new layer, but am having trouble centering and properly displaying the right amount of layers. (My pyramid is centered poorly and it isn't symmetrical. Here is my code right now. I added some comments.
For some context, I'll include the a picture of how I want the pyramid to look.
As you can see, when the user enters 4 for instance, there are 4 layers, and each layer increases by two on each side. However, with my current code, when the user enter a 4, there aren't four layers and I'm not sure how to achieve that. Please don't use CSS to achieve the centering, I want to keep it JavaScript only.
var num = prompt("Enter a number..");
for (var i = 1; i <= num; i = i + 2) {
for (var j = 1; j <= (num - i); j = j + 1) {
document.write(" ");
}
for (var k = 1; k <= i; k = k + 1) {
document.write("* ");
}
document.write("<br/>");
}
Upvotes: 0
Views: 165
Reputation: 125
you need to fix the spaces of course but the reason you can't get the expected number of rows is you are increasing i +2. i needs to be i++
EDIT: Spaces are also fixed.
var num = prompt("Enter a number..");
for (var i = 1; i <= num; i++) {
for (var j = 0; j < num-i; j++) {
document.write(" ");
}
for (var k = 1; k <= i; k++) {
document.write("*");
}
document.write("<br/>");
}
Upvotes: 1
Reputation: 797
You should think it is a matrix and each row length depends with your layer bunber which formula is n*2-1 and set to it in middle of row length
Upvotes: 0