Loop patterns: sums, counting down and more
A loop on its own just repeats. Most real loops build up an answer one step at a time: a total, a count, a product, a line of text. This lesson collects the patterns you'll meet in class and in exams, and traces each one step by step so you can see exactly what happens.
Iteration: one trip round the loop
Each pass through a loop's body is called an iteration. The loop variable (i below) holds a different value on each iteration:
for (let i = 1; i <= 3; i++) {
console.log("Iteration number", i);
}
console.log("Loop finished");Here is what happens, in order. Writing this out is called tracing the loop, and it's the best way to understand any loop:
| Step | i | Is i <= 3? | What runs |
|---|---|---|---|
| start | 1 | yes | prints "Iteration number 1", then i++ |
| 2 | 2 | yes | prints "Iteration number 2", then i++ |
| 3 | 3 | yes | prints "Iteration number 3", then i++ |
| 4 | 4 | no | the loop stops; "Loop finished" prints |
The condition is checked before every iteration, so the body ran 3 times, and i ended at 4.
Adding up: the sum of 1 to 10
To add numbers with a loop you need a variable that holds the running total. It's called an accumulator, and the pattern always has three parts:
let sum = 0; // 1. start the total at 0, BEFORE the loop
for (let i = 1; i <= 10; i++) {
sum = sum + i; // 2. add this number to the total
}
console.log("Sum of 1 to 10 =", sum); // 3. use the total AFTER the loopsum = sum + i is usually written sum += i. Trace the first few iterations:
| i | sum before | sum + i | sum after |
|---|---|---|---|
| 1 | 0 | 0 + 1 | 1 |
| 2 | 1 | 1 + 2 | 3 |
| 3 | 3 | 3 + 3 | 6 |
| 4 | 6 | 6 + 4 | 10 |
| ... | ... | ... | ... |
| 10 | 45 | 45 + 10 | 55 |
To watch the total grow, print it inside the loop:
let sum = 0;
for (let i = 1; i <= 10; i++) {
sum += i;
console.log(`after adding ${i}, the total is ${sum}`);
}Counting down: 10 to 1 in reverse
To go backwards, change all three parts of the for: start high, keep going while it's still at least the end, and subtract each time.
for (let i = 10; i >= 1; i--) {
console.log(i);
}
console.log("Lift off!");| Part | Counting up | Counting down |
|---|---|---|
| start | let i = 1 | let i = 10 |
| condition | i <= 10 | i >= 1 |
| step | i++ | i-- |
Getting the condition wrong is the most common bug: i <= 1 would be false straight away (10 is not <= 1), so the loop wouldn't run at all.
The sum of 1 to 10, in reverse
Add the numbers going down from 10 to 1. The total is the same 55, because the order of addition doesn't change the result, but the running totals are different:
let sum = 0;
for (let i = 10; i >= 1; i--) {
sum += i;
console.log(`added ${i}, total is ${sum}`);
}
console.log("Sum of 10 down to 1 =", sum);Printing the numbers on one line
console.log always starts a new line, so build a string first and print it once:
let line = "";
for (let i = 10; i >= 1; i--) {
line += i + " ";
}
console.log(line.trim());The same countdown with while:
let n = 10;
while (n >= 1) {
console.log(n);
n--; // forget this and the loop never ends
}Sums with a condition: even and odd numbers
Put an if inside the loop to add only some numbers. i % 2 === 0 is true for even numbers (the remainder after dividing by 2 is 0):
let evens = 0;
let odds = 0;
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) {
evens += i;
} else {
odds += i;
}
}
console.log("Sum of even numbers:", evens); // 2 + 4 + 6 + 8 + 10
console.log("Sum of odd numbers:", odds); // 1 + 3 + 5 + 7 + 9You can also skip the odd numbers entirely by starting at 2 and stepping by 2:
let evens = 0;
for (let i = 2; i <= 10; i += 2) {
evens += i;
}
console.log(evens);Counting how many
A counter is an accumulator that adds 1 instead of the number itself:
let count = 0;
for (let i = 1; i <= 100; i++) {
if (i % 7 === 0) {
count++;
}
}
console.log(count, "numbers from 1 to 100 divide exactly by 7");Multiplying: the factorial
The factorial of 5, written 5!, is 5 × 4 × 3 × 2 × 1. It's an accumulator too, but for multiplying, so it must start at 1: starting at 0 would make every answer 0.
const n = 5;
let fact = 1;
for (let i = 1; i <= n; i++) {
fact *= i;
}
console.log(`${n}! = ${fact}`);Times tables
const n = 7;
for (let i = 1; i <= 10; i++) {
console.log(`${n} x ${i} = ${n * i}`);
}Totals over an array: sum, average and largest
const marks = [72, 85, 90, 64, 88];
let total = 0;
let highest = marks[0];
for (const m of marks) {
total += m;
if (m > highest) highest = m;
}
console.log("Total:", total);
console.log("Average:", total / marks.length);
console.log("Highest:", highest);Note highest starts at the first mark, not at 0: if every mark were negative, starting at 0 would give the wrong answer.
Taking a number apart: digit sum and reverse
% 10 gives the last digit of a number, and Math.floor(n / 10) removes it. Repeat until nothing is left:
let n = 4096;
let digitSum = 0;
let reversed = 0;
while (n > 0) {
const digit = n % 10; // the last digit
digitSum += digit;
reversed = reversed * 10 + digit;
n = Math.floor(n / 10); // drop the last digit
}
console.log("Digit sum:", digitSum); // 4 + 0 + 9 + 6
console.log("Reversed:", reversed);| n | digit | digitSum | reversed |
|---|---|---|---|
| 4096 | 6 | 6 | 6 |
| 409 | 9 | 15 | 69 |
| 40 | 0 | 15 | 690 |
| 4 | 4 | 19 | 6904 |
Your turn: sum of 1 to n
This version asks how far to count. Change the number in the Input box and run it again:
const n = Number(prompt("Add up 1 to which number?"));
let sum = 0;
for (let i = 1; i <= n; i++) {
sum += i;
}
console.log(`1 + 2 + ... + ${n} = ${sum}`);
console.log("Formula check:", (n * (n + 1)) / 2);