Reputation:
I have made this guessing numbers, if one writes any other number than between 10 and 20 it will show them accordingly, but I want that it shows odd numbers.
For example, when I write 1, 2 ,3 and then 10, it will print 1, 2, 3 and 10, but I want it print every second number like this: 1, 3 and then 10 which is correct one.
I've tried many things, but couldn't make it work.
var luku;
luku = Number(prompt("number"));
while (luku < 10 || luku > 20) {
document.write(luku + "<br>");
luku = Number(prompt("give number"));
}
document.write(" correct " + luku);
Upvotes: 0
Views: 223
Reputation: 10697
You can check before appending the number to the document like:
if ((luku % 2) !== 0){
// Then add only
}
To display every second element from an array and exist integer:
var luku;
var list = [];
luku = Number(prompt("number"));
var last;
while (luku < 10 || luku > 20) {
last = luku;
list.push(luku);
luku = Number(prompt("give number"));
}
var listToDisplay = list.filter(a=>list.indexOf(a)%2===1)
listToDisplay.push(luku);
document.write(" correct " + listToDisplay);
To display Odd numbers from user input:
var luku;
var list = [];
luku = Number(prompt("number"));
while (luku < 10 || luku > 20) {
if ((luku % 2) !== 0){
document.write(luku + "<br>");
}
luku = Number(prompt("give number"));
}
document.write(" correct " + luku);
Upvotes: 1
Reputation: 28455
Try following using a counter
variable which is incremented everytime in the loop and based on that (odd values) paints text.
var luku;
var counter = 1;
luku = Number(prompt("number"));
while (luku < 10 || luku > 20) {
// paint for odd values
if(counter%2) document.write(luku + "<br>");
counter++;
luku = Number(prompt("give number"));
}
document.write(" correct " + luku);
Upvotes: 3
Reputation: 5362
I added a switch odd
which flips every time a guess happens, so it only shows the odd ones.
let guess
let odd = true
guess = Number(prompt('number'))
while (guess < 10 || guess > 20) {
if (odd) document.write(guess + '<br>')
odd = !odd
guess = Number(prompt('Enter a number'))
}
document.write(' correct ' + guess)
Upvotes: 0