Computer Science · Chapter 1 · Writing Code

Loops — Repeating Work in Code

How to tell a computer to do something many times — without writing it out many times.


bookSHelf  ·  Introduction to Computer Science  ·  §1.2  ·  a self-paced section

Loops · bookSHelf CS§1.2

By the end of this section you will be able to

Objectives

01

See what a loop is and why it beats copy-paste.

02

Write a for loop — init, condition, update.

03

Write a while loop, and know when to use each.

04

Loop over the items of a list.

05

Count and accumulate — a sum, a max, a tally.

06

Nest loops and dodge the common pitfalls.

Loops · bookSHelf CS§1.2

The opening problem — doing the same thing over and over

Say hello five times

The hard way — copy and paste

console.log("hello");
console.log("hello");
console.log("hello");
console.log("hello");
console.log("hello");

Five lines. Now imagine a thousand.

The loop way — say it once, repeat it

for (let i = 0; i < 5; i++) {
  console.log("hello");
}

Three lines — and changing 5 to 1000 is a one-character edit.

Loops · bookSHelf CS§1.2

The idea in one sentence

What is a loop?

Definition — loop

A loop is an instruction that runs the same block of code again and again — until a condition tells it to stop.

The body and the repeat

The code inside the braces is the body. The loop runs the body, checks whether to keep going, and if so runs it again. Each pass is one iteration.

1.2

Every loop, underneath, answers three questions

Where do I start?   Should I keep going?   What comes next?

Loops · bookSHelf CS§1.2

The for loop packs all three questions into one line

The for loop

A counting loop — prints 0, 1, 2, 3, 4

for (let i = 0; i < 5; i++) {
  console.log(i);
}

Three parts, in order

  • Initlet i = 0: start the counter (runs once).
  • Conditioni < 5: keep going while true.
  • Updatei++: step the counter after each pass.
Loops · bookSHelf CS§1.2

Follow the counter, one pass at a time

Tracing a for loop

The loop

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Read across each row: check the condition, run the body, then update.

Table 1.2.1 — the trace

passii ≤ 5?prints
11yes1
22yes2
33yes3
44yes4
55yes5
66no— stop
Loops · bookSHelf CS§1.2

When you don't know the count in advance

The while loop

Double until past 100

let n = 1;
while (n <= 100) {
  n = n * 2;
}
console.log(n);   // 128

When to reach for while

A while loop just repeats while a condition holds — no counter required. Use it when the number of passes depends on what happens inside the loop, like "keep doubling until we pass 100."

Loops · bookSHelf CS§1.2

Same idea, two shapes — pick by what you know

for vs while

Reach for for when…

…you know how many times, or you're stepping a counter over a range or a list — "do this for each ii from 0 to n1n-1." The count is built into the loop header.

Reach for while when…

…you'll stop on a condition, not a count — "until the user quits," "until the number is small enough." You may loop zero times, or many.

Loops · bookSHelf CS§1.2

Two words that change the flow

Stopping early: break & continue

break — leave the loop now

for (let i = 1; i <= 10; i++) {
  if (i === 5) break;
  console.log(i);   // 1 2 3 4
}

continue — skip to the next pass

for (let i = 1; i <= 5; i++) {
  if (i % 2 === 0) continue;
  console.log(i);   // 1 3 5
}
Loops · bookSHelf CS§1.2

The most common job a loop does

Looping over a list

Visit every item

let fruits = ["apple", "pear", "plum"];
for (let i = 0; i < fruits.length; i++) {
  console.log(i + ": " + fruits[i]);
}

Or, shorter: for (let f of fruits) { … }

Output

0: apple
1: pear
2: plum

The counter ii doubles as the item's position (its index).

Loops · bookSHelf CS§1.2

Try it now — trace it in your head first

Try it now — what does this print?

Try It Now 1 — a counter that goes down

for (let i = 3; i > 0; i--) {
  console.log(i);
}
console.log("go!");

The counter starts at 3 and steps down while it stays above 0.

3, 2, 1, go!

A countdown. When ii hits 0 the condition i>0i \gt 0 is false, so the loop stops — then the last line runs.

Loops · bookSHelf CS§1.2

The pattern behind almost every useful loop

Accumulate — a running total

Worked Example 1.2.1 — add up a list

let nums = [4, 8, 15, 16, 23, 42];
let total = 0;
for (let x of nums) {
  total += x;
}
console.log(total);   // 108

Start an accumulator at 0, then add each item as the loop visits it.

Keep a variable outside the loop

total lives outside so it survives every pass; the body just grows it. Sum, product, max, count — all follow this same shape.

Loops · bookSHelf CS§1.2

Same shape, different job

Find the largest value

Worked Example 1.2.2 — the running max

let nums = [4, 8, 15, 16, 23, 42];
let max = nums[0];
for (let x of nums) {
  if (x > max) max = x;
}
console.log(max);   // 42

Guess the first item is biggest, then let the loop correct you.

Remember the best so far

Each pass compares one item to the current champion and updates if it's bigger. After the last item, max holds the winner.

Loops · bookSHelf CS§1.2

Counting only the items that match

Count with a condition

Worked Example 1.2.3 — how many are even?

let nums = [4, 8, 15, 16, 23, 42];
let evens = 0;
for (let x of nums) {
  if (x % 2 === 0) evens++;
}
console.log(evens);   // 4

A tally is a sum that only counts the hits.

Add an if inside the loop

The loop visits every item; the if decides which ones count. Here 4,8,16,424, 8, 16, 42 are even — four of them.

Loops · bookSHelf CS§1.2

What a loop can total in the blink of an eye

5050

the sum 1+2++1001 + 2 + \cdots + 100, computed by a loop in exactly 100 steps — one addition per pass.

1+2++100=1001012=5050. 1 + 2 + \cdots + 100 = \frac{100 \cdot 101}{2} = 5050.

The loop doesn't need the formula — it just adds one number at a time. But it's a nice check that the loop and the arithmetic agree.

Loops · bookSHelf CS§1.2

A loop inside a loop

Nested loops

Rows and columns

for (let r = 1; r <= 3; r++) {
  for (let c = 1; c <= 3; c++) {
    console.log(r, c);
  }
}

The inner loop runs in full, every time

For each pass of the outer loop, the inner loop runs start to finish. Three outer passes × three inner passes = nine lines. Nested loops are how we handle grids, tables, and pairs.

Loops · bookSHelf CS§1.2

A concrete nested-loop example

A multiplication grid

Build each row, then print it

for (let r = 1; r <= 3; r++) {
  let row = "";
  for (let c = 1; c <= 3; c++) {
    row += (r * c) + " ";
  }
  console.log(row);
}

Output

1 2 3
2 4 6
3 6 9

Outer loop = the row; inner loop = the columns across that row.

Loops · bookSHelf CS§1.2

The inner count can depend on the outer counter

Printing a triangle

One more star each row

for (let r = 1; r <= 4; r++) {
  console.log("*".repeat(r));
}

Output

*
**
***
****

Row rr prints rr stars — the shape grows with the counter.

Loops · bookSHelf CS§1.2

Try it now — add them up

Try it now — how many stars?

Question. The triangle loop runs rows 11 through 44, printing rr stars on row rr. How many stars does it print in total?

10 stars

Row by row that's 1+2+3+4=101 + 2 + 3 + 4 = 10. Extend it to 10 rows and you'd print 1+2++10=551+2+\cdots+10 = 55 — the same running-sum pattern from earlier.

Loops · bookSHelf CS§1.2

The most common loop bug of all

Pitfall — off by one

Bug — runs one time too many

let a = [10, 20, 30];
for (let i = 0; i <= a.length; i++) {
  console.log(a[i]);   // ...30, undefined
}

Indexes are 0,1,20,1,2 — but i3i \le 3 also tries a[3]a[3], which doesn't exist.

Fix — stop before the length

let a = [10, 20, 30];
for (let i = 0; i < a.length; i++) {
  console.log(a[i]);   // 10, 20, 30
}

Use <, not <=, when looping to length.

Loops · bookSHelf CS§1.2

A loop that never ends

Pitfall — the infinite loop

Bug — the counter never moves

let i = 0;
while (i < 5) {
  console.log(i);
}   // i stays 0 — forever

Fix — make progress toward the exit

let i = 0;
while (i < 5) {
  console.log(i);
  i++;   // now it reaches 5 and stops
}

Every loop needs a reason to stop: a counter that advances, or a condition that eventually turns false. Forget it and the program hangs.

Loops · bookSHelf CS§1.2

Try it now — read carefully before you decide

Try it now — spot the bug

Try It Now 3 — sum 1 through 10?

let sum = 0;
for (let i = 1; i < 10; i++) {
  sum += i;
}
console.log(sum);

It looks like it sums 11 through 1010 — but read the condition.

Off by one — it stops at 9

i < 10 never lets ii reach 10, so it prints 4545, not 5555. Use i <= 10.

Loops · bookSHelf CS§1.2

Try it live — edit the code and run it, right here

Run the code yourself

Editor — a loop that sums 1..n, then draws a triangle

runs in your browser — edit freely, then Run

Output — console.log appears here

▶ Press Run to see the output…
Loops · bookSHelf CS§1.2

Everything you just learned, in one breath

Recap

  1. A loop runs a body again and again until a condition stops it.
  2. for when you know the count or step a counter; while when you stop on a condition.
  3. Keep an accumulator outside the loop to sum, find a max, or tally.
  4. Nest loops for grids and patterns; the inner loop runs fully each outer pass.
  5. Watch for off-by-one and the infinite loop — always give the loop a way to stop.
Loops · bookSHelf CS§1.2
1.2

Conclusions

What to carry forward

The core idea

A loop trades repetition for a tiny bit of bookkeeping — a counter or a condition. Once you can read the three parts of a loop, most real programs stop looking mysterious.

Keep practising

The Try It Live editor is yours — change n, print a bigger triangle, sum only the odd numbers. The fastest way to trust a loop is to run it.

You can now write for and while loops, loop over lists, accumulate results, nest loops, and avoid the classic bugs.   Next: §1.3 Functions — packaging code you can reuse.   Back to start.