Loops and functions

Video lessonComing soon

1 One step, many times

Our running problem is small. We count the numbers from 1 to n that are divisible by 3 or by 5. For n = 6, those numbers are 3, 5 and 6, so the answer is 3.

One if per number works for n = 6 and fails for every other n. The input can be any size, but the code has a fixed length. So the code must run the same check again and again, once for each number.

A loop does this. It repeats a block of code, called the loop's body, with one variable changing each time. Whenever a problem says "for each number", the code needs a loop.

2 Reading a loop's bounds

The most common loop is the for loop. A loop over 1 to n looks like this:

for (int i = 1; i <= n; i++) {
    check i
}

The header has three parts:

  • Start. int i = 1 runs once, first.
  • Stop. i <= n is checked before each run. When it is false, the loop ends.
  • Step. i++ adds 1 to i after each run.

For n = 6, the body runs with i from 1 to 6. At i = 7, the check fails and the loop ends.

To read any loop, we find the first and the last value the body sees. When i goes up by 1 from a to b, the body runs b − a + 1 times.

Loop headerValues of iRunsFor n = 6
i = 1; i <= n; i++1 to nn6
i = 0; i < n; i++0 to n − 1n6
i = 1; i < n; i++1 to n − 1n − 15
i = 0; i <= n; i++0 to nn + 17
i = n; i >= 1; i--n down to 1n6

The second row is the usual loop over array positions, 0 to n − 1.

4071-2293-5435first ilast i
n = 6 values sit at positions 0 to 5, so the loop stops before i = 6

A loop that runs once too many or too few has an off-by-one error. It comes from mixing up < and <=, or from starting at 0 when the problem starts at 1.

3 Counting multiples of 3 or 5

For each i from 1 to n, we check whether 3 or 5 divides it. i % 3 == 0 means 3 divides i with no remainder. If either check is true, we add 1 to count. A trace for n = 6:

ii % 3i % 5Counted?count
————0
111No0
222No0
303Yes1
414No1
520Yes2
601Yes3

The body runs six times, once per row. count grows only where a remainder is 0, and the loop returns 3.

Python's range(a, b) and Rust's a..b stop before b, like i < b. To include n, they write range(1, n + 1) and 1..=n.

n = 6 catches both off-by-one errors, because 6 itself counts:

  • Stop at i < n. The loop never sees 6 and returns 2.
  • Start at i = 0. The loop also checks 0. 0 % 3 is 0, so it returns 4.

4 The while loop

A for loop fits when we know the range before the loop starts. Sometimes we only know when to stop. For example, we count how many times we can halve n, with whole-number division, before it reaches 1. For n = 20, the values go 20, 10, 5, 2, 1, so the answer is 4.

A while loop has only the stop check. It runs the body again and again, as long as the check is true.

StartRead nsteps = 0n > 1?n = n / 2steps = steps + 1Print stepsEndNoYes
Yes runs the two steps on the right, then asks again
steps = 0
while n > 1
    n = n / 2
    steps = steps + 1
return steps
nstepsn > 1?
200Yes
101Yes
52Yes
23Yes
14No

Whole-number division drops the fraction, so 5 / 2 gives 2. In C++, n / 2 does this when n is an int.

Nothing in a while loop forces the step. If the body never changes n, the check stays true forever, and the program gets Time Limit Exceeded (TLE). So in every while loop, we find the line that moves it towards its stop.

5 Arrays, break and continue

Most loops in DSA walk over an array. A loop by index walks the positions 0 to n − 1 and reads nums[i]. A loop by value hands us each value in turn.

LanguageBy indexBy value
C++for (int i = 0; i < n; i++)for (int x : nums)
Javafor (int i = 0; i < nums.length; i++)for (int x : nums)
Pythonfor i in range(len(nums)):for x in nums:
JavaScriptfor (let i = 0; i < nums.length; i++)for (const x of nums)
Gofor i := 0; i < len(nums); i++for _, x := range nums
Rustfor i in 0..nums.len()for &x in &nums
C#for (int i = 0; i < nums.Length; i++)foreach (int x in nums)

We loop by value when only the values matter, as in a sum. We loop by index when we need the position, a neighbour such as nums[i + 1], or a change to nums[i].

Two keywords change how a loop runs. Here they work on nums = [4, 7, -2, 9, -5]:

4071-2293-54break
break stops at the first negative; positions 3 and 4 are never read
  • break ends the whole loop. To find the first negative, we stop at i = 2. Without break, the loop carries on to −5 and reports position 4, the last negative instead of the first.
  • continue skips to the next value. To add only the values that are not negative, we continue past each negative. The total is 4 + 7 + 9 = 20.

6 Loops inside loops

A loop can sit inside the body of another loop. This is a nested loop. For every run of the outer loop, the inner loop runs from its start to its stop.

Two dice show how it works. We count the ways to roll a total of 7:

ways = 0
for a from 1 to 6
    for b from 1 to 6
        if a + b == 7
            ways = ways + 1
234567345678456789567891067891011789101112
Row a, column b, cell a + b: 36 cells, 6 of them make 7

The inner body runs 6 times for each of the 6 values of a, so 36 times in all. That covers every pair of dice once, and six pairs add up to 7.

The counts multiply. An outer loop of n runs around an inner loop of m runs does n × m runs of the inner body. At n = m = 10⁵ that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit and gets TLE.

7 Functions

A function gives a piece of work a name. It takes values in through its parameters, does the work, and hands back a return value.

When code calls a function, the caller waits. At return, the function hands back its value, and the caller carries on.

A return ends the function at once, even inside a loop. This function returns the first negative's position as soon as it finds one, and −1 after the loop if there is none.

For [4, 7, -2, 9, -5], it returns 2 and never looks at 9 or −5.

A common mistake puts the "not found" answer inside the loop:

for i from 0 to n - 1
    if nums[i] < 0
        return i
    else
        return -1        // wrong

For [4, -2], this returns −1 after looking only at 4, but the answer is 1. A value is missing only once the loop has checked every value, so return -1 goes after the loop.

The habit to keep: before running a loop, say its first value, its last value and how many times its body runs. Most loop bugs show up in that one sentence.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.