Count-controlled loops - using FOR
Sometimes an algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. needs to iterationIn computer programming, this is a single pass through a set of instructions. steps a specific number of times. In programming, count-controlled loops are implemented using FOR statementThe smallest element of a programming language which expresses an action to be carried out.. PythonA high-level programming language. uses the statements for and range (note the lowercase syntax that Python uses):
- for determines the starting point of the iteration
- range states how many times the program will iterate
Consider this simple algorithm for adding up five inputted numbers:
- set the total to 0
- repeat this section five times
- input a number
- add the number to the total
- go back to step 2
- say what the total is
This algorithm would allow five numbers to be inputted and would work out the total. A count-controlled loop would be used because it is known, in advance, how many times the algorithm needs to loop.
The Python (3.x) code for this algorithm would look like this:
total = 0
for count in range(5):
number = int(input("Type in a number: "))
total = total + number
print("The total is: ")
print(total)
Steps that are part of the loop are indentingAdding spaces or tabs in front of blocks of code, making it easier for programmers to see which parts of the code relate to each other.. Indentation tells the computer which steps are to be iterated.
The program works like this:
- The program uses the variable ‘count’ to keep track of how many times the iteration has occurred.
- The ‘for’ statement is used to specify where the loop starts.
- The ‘range’ statement specifies how many times the loop is to happen.
- The variable ‘count’ controls the iteration.
- With each iteration, Python automatically adds 1 to the value of ‘count’.
- The program keeps iterating as long as the value of ‘count’ is in the range specified in the loop (in this case as long as ‘count’ is in the range 0 to 5). Once it reaches the end of the range (5) the iteration stops.
This program iterates five times. To have a different number of iterations, the value ‘5’ would simply have to be changed to the number of times required.