Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
Correcting the loop
Something went wrong, and instead of printing pages one through seven, the driver reports that page 0 was not found and then prints pages one through six. Let’s look at the sequence in which the parts of the for structure are implemented using this example:
for (var i = 0; i < 5; i = i + 1) {
console.log(i);
}- First,
var i = 0;works.ivariable will be created, which is equal to0. - Then the
i < 5;test will be performed. Sinceiis now equal to0and this value is less than5, the condition returnstrue. This means that the loop can continue working and go to execution of the code from the body of the loop. - The code will be executed from the body of the loop. In our case, the console will log
0, the current value of theivariable. - Then
i = i + 1will be executed. The variableibecomes equal to1. - Then
i < 5;will be tested. It will returntrueonce again, since1is less than5. - The loop body runs again, then
iincreases by one. This repeats untili < 5isfalse. The loop then stops.
Now let’s look at the example from the previous task. Why did the driver report that page 0 was not found?
On the first go-round or, scientifically speaking, during the first iteration of the loop, variable page still equals zero. And it increases to one already after the first iteration. If you change the initial value of the variable page from 0 to 1, then the problem disappears.
Why are there six pages, and not seven? Let’s take a look at the loop step-by-step:
Preparation: totalPages = 7; page = 0
1 iteration: page = 0; 0 < 7? yes! Reporting that page 0 was not found; page = 1
2 iteration: page = 1; 1 < 7? yes! Printing page 1; page = 2
3 iteration: page = 2; 2 < 7? yes! Printing page 2; page = 3
4 iteration: page = 3; 3 < 7? yes! Printing page 3; page = 4
5 iteration: page = 4; 4 < 7? yes! Printing page 4; page = 5
6 iteration: page = 5; 5 < 7? yes! Printing page 5; page = 6
7 iteration: page = 6; 6 < 7? yes! Printing page 6; page = 7
Check 8: page = 7; 7 < 7? no! Finish the loop!To get the seventh page, you need to change the comparison from “less than” to “less than or equal to”. In this case, the check on the eighth iteration of the loop will work and the seventh page will be printed.
8 iteration: page = 7; 7 <= 7? yes! Printing page 7; page = 8 Next check: page = 8; 8 <= 7? no! Finish the loop!
To summarize: to make everything print as it should, we need to start counting from page number 1 and use the <= sign in condition to include the last page in the loop.
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Comments