CodeMIRAI
0 XP

Loop patterns: sums, counting down and more

4 min read 15 runnable examples Quiz included

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:

JavaScript
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:

StepiIs i <= 3?What runs
start1yesprints "Iteration number 1", then i++
22yesprints "Iteration number 2", then i++
33yesprints "Iteration number 3", then i++
44nothe 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:

JavaScript
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 loop

sum = sum + i is usually written sum += i. Trace the first few iterations:

isum beforesum + isum after
100 + 11
211 + 23
333 + 36
466 + 410
............
104545 + 1055

To watch the total grow, print it inside the loop:

JavaScript
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.

JavaScript
for (let i = 10; i >= 1; i--) {
  console.log(i);
}
console.log("Lift off!");
PartCounting upCounting down
startlet i = 1let i = 10
conditioni <= 10i >= 1
stepi++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:

JavaScript
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:

JavaScript
let line = "";
for (let i = 10; i >= 1; i--) {
  line += i + " ";
}
console.log(line.trim());

The same countdown with while:

JavaScript
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):

JavaScript
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 + 9

You can also skip the odd numbers entirely by starting at 2 and stepping by 2:

JavaScript
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:

JavaScript
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.

JavaScript
const n = 5;
let fact = 1;
for (let i = 1; i <= n; i++) {
  fact *= i;
}
console.log(`${n}! = ${fact}`);

Times tables

JavaScript
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

JavaScript
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:

JavaScript
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);
ndigitdigitSumreversed
4096666
40991569
40015690
44196904

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:

JavaScript
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);
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.