Iteration using while (Part 3)
Repeated greetings
As an example of a program that has repetition, suppose we wish to be able to specify a greeting and number of times it should be printed: print("Happy Birthday!!!") print("Happy Birthday!!!") print("Happy Birthday!!!") print("Happy Birthday!!!")
This would result in multiple print statements, all with the same value being printed: print("Wishing you a festive spring!") print("Wishing you a festive spring!") print("Wishing you a festive spring!") print("Wishing you a festive spring!") print("Wishing you a festive spring!")
To make this into a function, we'll specify two parameters, the saying and the number of repetitions.
Starting with the function header, we consider what the condition should be. define greeting(saying, repetitions) while repetitions > 0 print(saying) repetitions ← repetitions - 1
Repetitions is the number of times we want to repeat printing, so we'd like a condition that will be true repetitions times before becoming false. Repetitions is the number of times we can subtract one from repetitions before reducing the value to zero. That is, we will enter the body of the loop to print while the value of repetitions remains greater than zero. In the body of the loop we will change the value of repetitions by subtracting one during each iteration and we'll print the saying.
To trace the function on inputs "Hello" and 3, i.e., greeting("Hello", 3), we see that the initial value of repetitions is the input value, namely 3. After the first iteration of the loop, since the condition is true, "Hello" is printed once and repetitions is decreased, receiving the new value 2. At the next iteration, the condition is still true, so "Hello" is printed gain and repetitions receives the value 1. This results in another iteration, after which repetitions is 0. There are now no further iterations since the condition is false.
Creating a while loop
We can summarize the steps as a recipe.
While loop recipe
- Express the task as iteration.
- Write a condition.
- Ensure initial values of variables checked in the condition.
- Ensure the condition can change in the body of the loop.
For our previous example, expressing the task as iteration was straightforward. This won't always be the case. Next, we figure out a condition that suits our needs. In our example, the initial value of the variable in the condition was part of the input to the function. In other situations, we might need to explicitly set it. And to make sure that it isn't an infinite loop, we make sure that the condition can change from true to false due to steps in the body of the loop.
Example: remainder
Let's use the recipe on the problem of finding a remainder. How does this use iteration? Let's start with the simpler problem of finding iteration in multiplication. We can view multiplication as repeatedly adding the same number into the result. For example, the products of 4 and 5 can be found by adding 5 repeatedly: 5, 10, 15, 20, ...
Similarly, division can be viewed as repeatedly subtracting a number from the result. The remainder is what is left when the second number can no longer be subtracted from the first. For example, the remainder when 10 is divided by 3 can be found by substracting 3 from 10 repeately until a number smaller than 3 is obtained: 10, 7, 4, 1.
Writing pseudocode for remainder
Let's write this as pseudocode using our recipe.
While loop recipe
- Express the task as iteration.
- Write a condition.
- Ensure initial values of variables checked in the condition.
- Ensure the condition can change in the loop body.
We already know how to express the task as iteration. To figure out the condition, we observe that we keep repeating as long as we can subtract second from first. That is, we keep repeating the steps while first is greater than or equal to second. We'll make this into a function, which means that the values of first and second are inputs. Finally, we make sure that the value of the condition can change. This happens naturally as we repeatedly subtract second from first. To complete the function, we return the remainder. define remainder(first, second) while first >= second first ← first - second return first
Example: quotient
As another example, we can determine the quotient of two numbers.
While loop recipe
- Express the task as iteration.
- Write a condition.
- Ensure initial values of variables checked in the condition.
- Ensure the condition can change in the loop body.
This time, we repeatedly subtract second from first and also repeatedly update the count of how many subtractions have taken place. The same condition is used for remainder works here and again we set the initial values as inputs to the function. Values are updated by subtraction. What about updating the count? We increment a counter inside the loop, but also ensure that it has an initial value before the loop is entered, and finally we return the result. define quotient(first, second) counter ← 0 while first >= second first ← first - second counter ← counter + 1 return counter
Example: searching in a string
As our last example, suppose we wish to find the position of the first occurrence of a character in a word. For example, if the word is "caterpillar", we want to use the index to examine a position, which we allow to go from 0 to one less than the length of the word. Note that the length of the word is 11. That is, we start with an index of zero and repeatedly add 1 to the value, allowing us to consider, in turn, "c", "a", "t", "e", "r", "p", "i", "l", "l", "a", and "r":
At the end of this process, index has the value 10, one less than the length of the string "catepillar", which is 11.
Creating the function
## Preconditions: ## word is a nonempty string ## char is a string of length 1 ## Postcondition: ## Returns index of first occurrence ## of char or length if absent define search(word, char) index ← 0 while index < length(word) if word[index] == char return index index ← index + 1 return index
As preconditions, we state that the string is nonempty and that the character is a string of length 1. The number returned is the index of the first occurrence of the specified characer or, if there are no such occurrences, the length of word. Following the recipe, we give a condition, namely that the index isn't past the end of the string. We make sure that index has an initial value and that its value can change. To process a position, we return the position if the specified character is found. If not, return the value of index after the last iteration of the loop, which will be the iteration when the condition is false, that is, index has the value equal to the length of word.