Tip: Choose Save as PDF in the print dialog to download. Use A4 paper size.
Shade in the A or B circle for each question.
let total = 0; be declared in sumTo(n)?return total; as the very first line inside the for loop body. What happens?Draw a line connecting each item on the left to its match on the right.
| Left column | Right column | |
|---|---|---|
| 1function sumTo(n) { let total = 0; for (let i = 1; i <= n; i++) { total += i; } return total; } | AThe total is declared outside the function, so it keeps its old value between calls and the second call gives a wrong, bigger answer. | |
| 2let total = 0; | BThe return is inside the loop, so the function stops after the first repeat and returns 1 instead of the full sum. | |
| 3The return must come after the loop ends, so the loop can finish adding every number first | CA function that loops from 1 up to n, adds each number to a total, then returns the finished total after the loop | |
| 4The loop uses the parameter n to decide how many times to repeat | DDeclares the accumulator inside the function so it starts at 0 every time the function is called | |
| 5function sumTo(n) { let total = 0; for (let i = 1; i <= n; i++) { total += i; return total; } } | Efor (let i = 1; i <= n; i++) { total += i; } return total; | |
| 6let total = 0; function sumTo(n) { for (let i = 1; i <= n; i++) { total += i; } return total; } | Ffor (let i = 1; i <= n; i++) |
Complete each line of code by filling in the missing parts.
Shade in the letter of the line that contains an error.
function sumTo(n) — A function that loops up to its parameter n, adds each number to a total declared inside it, then returns that total after the loop ends so the caller gets the finished answer.function sumTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) { }
return total;
}function sumTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) { for (let i = 1; i <= n; i++) {
total += i;
}// 1 + 2 + 3 + 4 gives 10
let result = sumTo(4);
console.log(result);