Counting steps
JavaScript · Unit 21: Complexity
- Full plan
- JavaScript
- 9 exercises
You don't need a stopwatch to tell whether a program is fast: you can count how many times it works.
A variable that goes up on every turn tells you.
function steps(n) {
let s = 0;
for (let i = 0; i < n; i++) {
s++;
}
return s;
}
console.log(steps(5));Prints
5
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Complete it so
ssays how many turns the loop took.3. Multiple choice
If
nis 100, how many times doess++run?4. Predict the output
This loop moves two at a time. What does it print?
5. Find the bug
steps(6)should give 6, because the loop takes 6 turns. Which line has the error?6. Put the lines in order
Build a counter that says how many items it went through.
7. Predict the output
filterkeeps the even ones. How many items did it look at?8. Multiple choice
Why do we count steps instead of measuring the seconds it takes?
9. Predict the output
Both ways add up 1 + 2 + … + 20. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.