Loops and functions
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 = 1runs once, first. - Stop.
i <= nis checked before each run. When it is false, the loop ends. - Step.
i++adds 1 toiafter 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 header | Values of i | Runs | For n = 6 |
|---|---|---|---|
i = 1; i <= n; i++ | 1 to n | n | 6 |
i = 0; i < n; i++ | 0 to n − 1 | n | 6 |
i = 1; i < n; i++ | 1 to n − 1 | n − 1 | 5 |
i = 0; i <= n; i++ | 0 to n | n + 1 | 7 |
i = n; i >= 1; i-- | n down to 1 | n | 6 |
The second row is the usual loop over array positions, 0 to n − 1.
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:
i | i % 3 | i % 5 | Counted? | count |
|---|---|---|---|---|
| — | — | — | — | 0 |
| 1 | 1 | 1 | No | 0 |
| 2 | 2 | 2 | No | 0 |
| 3 | 0 | 3 | Yes | 1 |
| 4 | 1 | 4 | No | 1 |
| 5 | 2 | 0 | Yes | 2 |
| 6 | 0 | 1 | Yes | 3 |
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 % 3is 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.
steps = 0
while n > 1
n = n / 2
steps = steps + 1
return steps
n | steps | n > 1? |
|---|---|---|
| 20 | 0 | Yes |
| 10 | 1 | Yes |
| 5 | 2 | Yes |
| 2 | 3 | Yes |
| 1 | 4 | No |
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.
| Language | By index | By value |
|---|---|---|
| C++ | for (int i = 0; i < n; i++) | for (int x : nums) |
| Java | for (int i = 0; i < nums.length; i++) | for (int x : nums) |
| Python | for i in range(len(nums)): | for x in nums: |
| JavaScript | for (let i = 0; i < nums.length; i++) | for (const x of nums) |
| Go | for i := 0; i < len(nums); i++ | for _, x := range nums |
| Rust | for 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]:
breakends the whole loop. To find the first negative, we stop ati = 2. Withoutbreak, the loop carries on to −5 and reports position 4, the last negative instead of the first.continueskips to the next value. To add only the values that are not negative, wecontinuepast 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
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
- Fizz BuzzEasy
- Multiplication tableEasy
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.