Reputation: 35
Write the JavaScript to prompt the user to enter an odd number. First, check that the user has entered a valid odd number. Then you need to print to the console a cross made of the same number of * characters as the number the user entered.
So far I have my code as such
I've edited my code to include the proper way
let num = prompt("Enter an odd number");
let star = "*";
let vertical = "";
let horizontal = star.repeat(num);
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let pos = +(Math.ceil(num/2));
// I need to divide the input number by 2 and round up
for (var h = 0; h < pos; h++){
vertical += (" ")
}
for (var v = 0; v < pos; v++){
vertical += vertical + "\n *"
}
vertical += "*"
console.log (vertical)
I can get vertical to \n the proper amount of times but how would I go about making sure I don't over repeat the *?
Upvotes: 0
Views: 1033
Reputation: 914
You're on the right track. There are three steps that you need to do here. You need to create a cross like this (assuming number is 13):
*
*
*
*******
*
*
*
You need to create Math.floor(13/4)
(comes out to 3) rows of a single star, with each star after Math.floor(13/4)
spaces. Then you need a row of Math.ceil(13/2)
stars starting at position 0. Lastly, you need the same number of stars as you did before that row, so you can just do the same thing again.
Using your code, I would do something like this:
let num = prompt("Enter an odd number");
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let star = " ";
let pos = Math.floor(num/4);
let vertical = star.repeat(pos) + "*";
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
console.log("*".repeat(Math.ceil(num/2)));
for (var i = 0; i < pos; i++) {
console.log(vertical);
}
Upvotes: 1
Reputation: 7739
Initially you are assigning
let vertical = "*";
change it to
let vertical = "";
Try this
let num = prompt("Enter an odd number");
let star = "*";
let vertical = "";
let horizontal = star.repeat(num)
while (num%2 == 0) {
console.log("User did not enter an odd number");
num = prompt("Enter an odd number");
}
console.log("User's number is " +num);
let pos = +(Math.ceil(num/2));
// I need to divide the input number by 2 and round up
for (var h = 0; h < pos; h++){
vertical += (" ")
}
console.log(vertical)
Upvotes: 1