I want to write javascript code to get an extra countdown
so this is basically a hint:
you enter the number, and the number of code must be added at the countdown, for example, if the user enters 10, then the result should be:
10 + 9 + 8 + 7 + 6 + 5 + 4 +3 +2 +1=55
.
This is what I have so far:
var num = Number(prompt("Enter a Number Greater than zero"));
while (num > 0){
first = num;
second = num-=1;
document.write(first + " +" + second + " +");
value = first + num;
document.write(value)
num--;
}
but i keep getting something like this: 4 +3 +72 +1 +3 (say 4 is the number the user enters)
I am stuck, can someone please help me ???? !!
+3
source to share
2 answers
You can change the algorithm a bit, because for the first value, you don't need a plus sign to output.
var num = Number(prompt("Enter a Number Greater than zero")),
value = 0;
document.body.appendChild(document.createTextNode(num));
value += num;
num--;
while (num > 0) {
document.body.appendChild(document.createTextNode(' + ' + num));
value += num;
num--;
}
document.body.appendChild(document.createTextNode(' = ' + value));
+2
source to share
You can store the total in one variable outside of the loop while
.
var num = Number(prompt("Enter a Number Greater than zero"));
var total = 0;
while (num > 0) {
total += num;
document.body.innerHTML += (num == 1 ? num + ' = ' + total : num + ' + ');
num--;
}
+2
source to share