简体   繁体   中英

Determine an Odd/even Number, And Use While Loop To Add From Counter in Javascript

I do not know why it stops looping after satisfying the condition sometime(eg.getting the sum of number from where it precedes). I believe that there's something wrong with the code. Where is it?

var init = parseInt(prompt('enter an odd or even no.'));
var sec = init%2;

if (sec != 0) {
    var loop = 5;   
    while (loop < 10) {
        var num = 1;
        loop += loop; 
        num += 2
    }
    document.write(num);
} else {
    document.write('None');
}   

Is this what you are trying to do? Variables declared with var don't have block scope, so it can be clearer to declare them all at the top of your code.

 var init = parseInt(prompt('enter an odd or even no.')); var sec = init % 2; var loop = 5; var num = 1; if(sec != 0) { while(loop < 10) { num+=2; loop++; document.write(num); } } else { document.write('None'); } 

The looping is happening, but you're just not seeing it because you don't print anything when it loops.

Your code should be like this instead:

var init = parseInt(prompt('enter an odd or even no.'));
var sec = init%2;

if (sec != 0) {
    var loop = 5;   
    while (loop < 10) {
        var num = 1;
        loop += loop; 
        num += 2
        document.write(num);
    }

} else {
    document.write('None');
} 

See that document.write(num) now is INSIDE your loop, so it will print every time it loops through.

Previously, it was set outside, so essentially what was happening is that you were only seeing the result AFTER the last iteration.

You need to initialize num with 1 outside of the while statement, because you assign this value for every loop.

The I suggest to declare all variable in advane at top of the code. You may assign here known values, too.

 var init = parseInt(prompt('enter an odd or even no.'), 10), sec = init % 2, loop = 5, num = 1; if (sec != 0) { while (loop < 10) { loop += loop; num += 2; } document.write(num); } else { document.write('None'); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM