Learning Outcomes
On completion of this section you will know how to use:
- for loops
- while loops
On completion of this section you will know how to use:
Iteration means doing something repeatedly, i.e. again and again. In programming it means repeating a group of programming lines a number of times. This is a major departure from the programs we have written so far.
The sequence of our programming has up to now gone from top to bottom. In the simple programs that we have looked at execution started at the first line and continued downwards to the last line. No line was skipped and no line was executed more than once. Also no line was executed until the previous line complted its task.
In Exerccise 4 of the page Expressions you were required to write a program that accepted the details of three transactions from a user. The required program would look somewhat like Listing 1 below.
This is a huge program, and we are only dealing with a very small number of customers. Imagine to size of a program that would deal with all of the customers that came into a busy store during the course of one day!
Is there a better way? Yes there is. Its called Iteration. It is also called loops.
There are two types of loops: for loops and while loops. The former is the simplest and therefore we will start with that.
Go to topListing 2 above performs exactly the same function as Listing 1, i.e. it accepts values for three sales and prints out the details of each single sale including the calculated values. But it is only 10 lines, so how does it do it?
Look at line 2 for intCounter in range(3):
. What does it mean?
Firstly the keyword for tells us that it is the start of a for loop. The next item intCounter is an integer variable that is used to keep track of how many times the loop has iterated. This variable is generally referred to as the 'loop counter' and normally the word 'counter' is part of its name, as in our example here. The penultimate part range(3) controls how many times the loop will iterate. The loop counter, intCounter in our case starts off at zero, then once the body of the loop has been executed once, its value is incremented by 1. The body of the loop is then executed one more time. This continues until the loop counter has a value equal to the value between the brackets of range(). Once this occurs the loop terminates.
Applying this to our example intCounter starts with a value of zero, then lines 3 - 16 are executed. Then intCounter is incremented to 1 and lines 3 - 10 are executed once more. Next intCounter is incremented to 2 and lines 3 - 10 are executed. After this intCounter is incremented to 3. This is the value between the brackets of range(), and therefor it provides the signal for the loop to stop iterating.
From the above we can summarise that in a simple loop like Listing 2 the loop counter starts off with a value of zero, then after each execution of the body of the loop the counter is incremented by 1. This continues until the loop counter has a value equal to that between the brackets of range(), after which the loop will stop iterating. Thus in Listing 2 the loop will iterate when intCounter has values of 0, 1 and 2 but stops when it reaches the value of 3.
Notice that lines 9 - 17 in listing 3 are identical to lines 2 - 10 in Listing 2. This means that the processing of the two programs is identical. From a pedagogical point of view however Listing 1 may give the impression that a for loop actually takes over the entire program and that every line of the program will be executed. This is not the case as shown by Listing 3. Here the loop is shown as being part of a larger program. Linees 2 - 8 and 19 - 20 are not part of the loop and will, therefore execute only once. Line 9 is the loop controller and lines 10 - 17 form the body of the loop. From line 9 we can deduce that the loop will iterate three times - with the loop counter having values of 0, 1 and 2 - and thus lines 9 - 17 will be the only lines that will be repeated.
Let us now look at the features of the loop as part of a larger program:
Before beginning on Iteration you would have been familiar with the concept of sequence, i.e. that program execution starts at the first line and continues downwards line by line until the final line is executed. Does iteration contradict this top to bottom sequence? No it does not; it simply adds some flexibility to the concept.
Examining Listing 3, we see that lines 2 - 8 will be executed in order. Control then passes to line 9 - the start of the loop. This loop extends down to line 17 and thus lines 9 - 17 will be executed three times. During each of those executions lines 9 - 17 will be executed in the strict order of their sequence. Once lines 9 - 17 has been executed three times lines 19 and 20 will be executed thus finishing the program.
Go to topIn Listing 2 and Listing 3 above we used a very unrealistic example; customers may want to purchase more than one item and different items will have different prices. As we don't know how many items each customer may buy we shall look at a program which, instead of iterating exactly three times will iterate for exactly as many times as the user requires.
Lines 4 - 10 in Listing 4 should be familiar by now and therefore we shall not discuss them. Instead we shall concentrate on lines 2, 4 and 11, i.e. the lines that control the body of the loop. The logic of how this loop works is that the user is asked to enter the name of a customer. If some text is entered then the program presumes that a customer's name has been entered and it will proceed to go into the body of the loop, i.e. lines 4 - 9. By the time that line 9 finishes execution
Line 2 gets the name of a customer from the keyboard and stores it in the variable strNameOfCustomer. Control now passes to line 3. This line could be translated into English as 'while name of customer is not a blank' What this means is that if the user has actually typed in a name then the value stored in strNameOfCustomer cannot be blank. If the user does not want to add any sales data then when they are asked for name of customer they will simply press the Enter key without entering any data. This will cause a blank to be stored in the variable strNameOfCustomer. If this is the case then the test 'while name of customer is not a blank' is false then the body of the loop, i.e. lines 4 - 11 are skipped, thus ending the program.
A typical run through this program would be as follows:
From the above we can deduce that as long as the user continues to supply peoples names when prompted the while loop will keep iterating, but once the user enters a blank the loop terminates.
Fig 1 below shows the running of the program when the user enters a name at line 2 and also enters names twice at line 11.
Again to emphasise that loops usually tend to be parts of a program and not the entire program we show below the same code as Listing 4 but as part of a larger program.
Fig 2 below shows the running of the code when the exact same values were entered as with Listing 4.
The exercises below are extensions of their equivalents in the lesson Variables.
A customer in a store buys a number of the same item. The data required for this transaction are:
Write a program that will allow three customers to be processed. For each ccustomer the program collects the above data from the user, stores each data item in an appropriately named variable and calculates the cost of the sale by multiplying the cost of an item by the number of items sold. It then prints out the data entered by the user as well as the calcculated value before processing the next customer. All data must be appropirately labelled. In the case of numeric data ensure that you use integers or floating point numbers correctly.
Repeat Exercise 1 except that this time an indefinite number of customers must be processed
Write a program that will collect data about a book. The data required include:
The program must store each data item in an appropritely named variable. Total sales is calculated by multiplying Price by Amount sold. Both the data entered by the user and the calculated values must be printed with appropriate labels.
The program must be able to process four books and the data for one book must be processed and printed out before moving to the next book.
Repeat Exercise 3 except that this time an indefinite number of books can be processed
Extend Exercise 3 so that the royalties for the author is calculated. The royalties are calculated as 10% of the total sales. Output must be similar to that for exercise 3 except that the royalties are also included.
Go to topYou are required to write a program that will collect details about five employees. The program will store each data item in an appropriately named variable. The data required are:
The value for hours worked should be an integer.
Once data entry is complete the Gross Pay is calculated by multiplying Hourly Rate by Hours Worked. Once the value of Gross Pay is calculated, Tax is calculated as 25% of the Gross Pay. Net Pay is calculated by subtracting Tax from Gross Pay. Both input value data and calculated values must be printed with appropriate labels.
Once the current employee is processed the system moves to the next employee until all employees are processed.
Repeat Part 1 but this time an indefinite number of employees can be processed
Go to top