Iteration using for (Part 2)

Example: replacing a character in a string

Let's look at a slightly more complicated example, this time creating a function that processes a string. Consider the string "banana":

b

0

a

1

n

2

a

3

n

4

a

5

Suppose we wish to create a new string by replacing each occurrence of the letter “a” by the letter “o”. We can process each character in turn, copying it to the new string if it is not an “a”, and otherwise using the letter “o”. We iterate through the positions in the string from 0 to one less than the length of the string:

b

0

o

1

n

2

o

3

n

4

o

5

Writing the function

For loop recipe

  • Express the task as iteration.
  • Specify starting and ending values.

This means to create our for loop, our starting and ending values are 0 and one less than the length of the string. define replace(word, old, new) new_word ← "" for index from 0 to length(word)-1 if word[index] == old new_word = new_word + new else new_word = new_word + word[index] return new_word

Inside the loop body, we check if the current character matches the character to replace. If so, we concatenate the replacement character to the new string. Otherwise, we concatenate the current character to the new_word. We return the new_word. But we're not done yet. We don't need to initialize the value of index since that is handled by the "for" loop. But notice that new_word appears on the right hand side of an assignment statement in the body of the loop. We need to give an initial value to new_word.

Caution

Ensure any variable used in the loop body has an initial value.

More generally, we need to check that any variable used in the body of the loop has an initial value.

Revisiting searching in a string

In all our examples so far, we have completed all our iterations before returning a value. But what about in a situation when we might want to exit before completing all the iterations, such as when we're looking for a value in a string or sequence and can stop when we've found it. Let's write the function twice for sake of comparison.

The function using the while loop: define search(word, char) index ← 0 while index < length(word) if word[index] == char return index index ← index + 1 return index

The function using the for loop: define search(word, char) for index from to length(word)-1 if word[index] == char return index return length(word)

The “while” loop uses a condition comparing an index to the length of the input, whereas in the “for” loop, it suffices to give the starting and ending values of the index. In the “while” loop, the new variable needs an initial value and needs to be updated inside the loop. These steps are not necessary when using a “for” loop. In both functions, we return the index if the characters match. If there is no match, we return the length of the string. In the “while” loop, we can return the index as the condition becomes false precisely when it is equal to the length of the string. For the "for" loop, however, index never has a value smaller than the starting value 0 or larger than the ending value length(word) - 1. So we need to compute the length of the string from the input. Why didn't we just add one to the last value of index?

Caution

A counter may not have a value after the loop ends.

We need to be careful. Depending on the programming language, a counter variable may not have a value outside the loop.

Uses of loops

We've seen only a few simple examples so far. What exactly can be done with “for” loop depends on the programming language.

The following are variants in some programming languages:

  • Count down:
    Some languages support counting both up and down.
  • Count by 2, 3, or other intervals:
    Some languages support counting by intervals such as 2, 3, or other interval.
  • Iterate over characters in a string:
    There may also be special ways to automatically specify that each character in a string be examined.
  • Iterate over elements in a sequence:
    There may also be special ways to automatically specify that each item in a sequence be examined.

The following are tricky parts about “for” loops:

  • Be sure to initialize any variable used in the loop body.
  • The counter is undefined before the loop starts.
  • Depending on the language, the counter may or may not have a value after the loop.

In using loops, remember that even though there are not variables used in the condition, since there isn't a condition in a “for” loop, there may be variables that need to be initialized before use in the loop body. This is also true for “while” loops. It is probably not a surprise that the counter won't have a value before the loop starts, but perhaps more surprising that it may also not have a value after the loop ends.