Program that calculates and shows the value of (2 to the 10th power)
This statement results in 1024. I'm not understanding how it keeps looping after it reaches "9". Does "< 10"
mean loop around ten times, or loop up to a sum less than "10"? Would appreciate someone explaining this to me. Thanks!
var result = 1;
var counter = 0;
while (counter < 10) {
result = result * 2;
counter = counter + 1;
}
show(result);
Your counter is running ten times, once each for the values 0-9. When writing loops like that (that include a <
) I think of the 10 as "this loop will be running ten times." It's helped a lot with minor issues like this.
Remember, there are only two really hard things in programming: cache validation, variable substitution, and off-by-one errors.
loop 1: result = 1*2 (2) counter = 1
loop 2: result = 2*2 (4) counter = 2
loop 3: result = 4*2 (8) counter = 3
...
loop 10: result = 512*2 (1024)counter = 10
It loops 10 times and as such it multiplies by two ten times and as such gives you 2^10 = 1024. Exactly. PS If you only want this multiplication, you'd be better off with
result = 1 << 10
Yes ten times 0 to 9 = 10.
When the compiler sees if 10 < 10 it evaluates to false. If you want to see 10 change the condition to <=
The program will only step inside the loop if the condition for the while-loop is met. So you check it before entering the loop.
If you want the program to step inside the loop one more time, either use a do-while loop where you check the condition after the execution of the loop. You can also change the condition to "counter <= 10" and use the while-loop as is.
Here you can find more information on while-/do-while-loops and also breaks in javascript.
When counter
is 1 it result
is 2^1 When counter
is 2 it result
is 2^2
Since counter
is 10
at the end of the loop, result
is 2^10
.
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.