0
Hi I need some help
I'm doing a task for JS, and I need to do with a while loop a count down, that has to be in this order: 4 3 2 1 0 The problem is that I don't know how to do it backwards like in the example, I know how to do it the normal way: 0 1 2 3 4 If anyone could help me out I'll appreciate it
15 Respuestas
+ 2
Yes, if you save it as Node.js code then it will trigger that error;
You'd have to save it as Web code.
+ 1
Looping forwards means to initialize loop counter by range start, and increment loop counter while loop counter is less than the range end.
Looping backwards means to initialize loop counter by range end, and decrement loop counter while loop counter is greater than the range end.
+ 1
It's pretty easy. We only need to change some things ...
The loop condition should check whether loop counter <seconds> is greater than or equal to zero, and we decrement the loop counter <seconds> rather than incrementing it.
while( seconds >= 0 )
{
document.write( seconds + "<br />" );
seconds--;
}
Tell me in case of any doubt ...
+ 1
Bob_Li thanks man it work with out the <br /> Cristo bless you
+ 1
Ipang thanks man for help me with the code, it means a lot wen you're learning, Crist bless you 👍
0
Ipang you are right but I don't know how to do it exactly, I have this code that do the loop:
function main() {
var seconds = parseInt(("4"), 10)
var x=0;
while (x<seconds) {
document.write(x + "<br />");
// break;
x++;
}
}
main();
The thing is that wen I try to decrease the counter it doesn't work, I do not run
0
Ipang ok I'm going to try it
0
Ipang for some reason when I run the code it says "reference error,document don't defined" and when I use (console.log) the results are in this way:
4<br />
3<br />
2<br />
1<br />
0<br />
0
Ipang yeah you right but when you're doing the task the code play ground have it set it as a Node.js
0
Ipang In the normal code play ground it works I don't know how to make it work
0
in code coach you use console.log
function main() {
var seconds = parseInt(readLine(), 10)
// Your code here
while(seconds>=0){
console.log(seconds);
seconds--;
}
}
0
Because you are incrementing with x++. You need decrement by x--
While (seconds !== 0) { seconds--; }
0
for (let x = 4; x >= 0 && x <= 4; x--) { console.log(x)}
But this is better way:
https://code.sololearn.com/Wb2Ei8G537i5/?ref=app
Thanks Justice Friday
0
Give starting value like i=4 then reduce it i--