Repetition structures is the formal name for loops. Loops allow programmers to do amazing things in short lines of code. Loops are great because they allow a piece of code to be executed mutliple times without assuming or guess how many times the repetition needs to happen. Loops are a conditional structure which does depend on true or false (relational) expressions to drive them. However, unlike decision structures that use the condition to execute a body and move on with the code (hence if), the loop with recheck the condition after an execution (call an iteration) and reiterate the execution if the condition is still true. In programming, these are typically called while
conditions.
On this page we will stay really high level and talk about loops in the following contexts: condition-controlled while loops, counting (for) loops, and nested loops. Once again, C++, Java, and C# will look very familiar in the structure of loops but Python will have a bit of a different approach.
Loops are also critical in future programming constructs such as arrays which are only sifted through using loops.
Every loop in code should follow the same steps in order to iterate properly. Let's start with this abstract example:
var loopControlVariable = initialValue
while (loopControlVariable == True) {
body
loopControlVariable = updatedValue
}
Every loop has what we refer to as a loop control variable. We can identify the loop control variable as the the variable situated in the while
statement. Once we identify the loop control variable the steps are as follows:
If the loop control variable is not updated int he body of the loop, the loop will be an infinite loop which is not what most programmer want. If a programmer really wants an infinite loop, they would write this:
while(true){
...
}
As we go through programming examples, note that the loop steps are always followed.
When a loop is condition-controlled that simply means that the code will continue iterating until some particular condition is met. Let's say for example that you are using the ATM and you have completed a transaction. The ATM shows a screen that says "Would you like to do something else?" This appears along with a Yes/No option. If you select yes, the program displays the options menu and you start all over again. If no is selected, the machine issues your card and ends your interaction.
Condition-controlled loops are considered indeterminate because we have no idea how many times the body wiil be executed, we just know that there is a proper condition to end the loop.
For our programming example let's consider a simple adder that will give the user the option to keep adding until they are satisfied.
Language | Code |
---|---|
C++ |
#include<iostream>
|
C# |
using System;
|
Java |
import java.util.Scanner;
|
Python |
endProgram = 'n'
|
Programming Notes: There are a few things going on and many of it to make the program work for us. You may notice that in Java and C# there is a string variable to receive keyboard input because those languages do not read characters directly from the keyboard. Python does not even have a character data type so we just treat the string like a character.
Looping Notes: endProgram
is the loop control variable initialized to 'n'
. The test condition (condition for the loop to run) is that the loop control variable is equal to (==
) 'n'
. The loop control variable needs to be updated inside the body of the loop. In our example the program asks for input and sets endProgram
to a new value. Here are the steps of program execution:
endProgram
to 'n'
.endProgram == 'n'
is true.endProgram
to the user's entry.while
statement is executed to see if the condition is still true. If it is, steps 3 and 4 are executed again. If not, the program moves on.While Python does not support do-while loops, these loops are built to where the body of the loop is executed at least once. The body of the loop is written before the condition. A google search for do-while loops will give you more tips on how to use them.
Counting loops are determinate repetition structures. We know how many times this loop will execute prior to the execution. We can use any loop construct (while) to execute a counting loop. However, the primary tool to use for counting is the for
loop. This loop is awesome since it takes all three steps of loop design and puts them in one header line. Let's take the example we worked with on the condition-controlled side and set the code so that the user will find the sum to 5 pairs of numbers.
Language | Code |
---|---|
C++ |
#include<iostream>
|
C# |
using System;
|
Java |
import java.util.Scanner;
|
Python |
for count in range(1, 6):
|
Notice that the initial condition, test condition, and how to count are included in the loop header in C++, C#, and Java. The body of the loop in these instances are a bit more simple than the body of while loops and do while loops because you do not have to worry about loop updates. C++, C#, and Java have the ++
operator that means increment. There is also a decrement operator --
. This ++
operator adds 1 to an int variable. So if x = 5
, then after x++
, x
= 6; The decrement operator is similar.
Python is a bit different. Python uses the in range()
function that can be created three ways
for count in range(5)
: where count
starts and 0 and goes to 4 (5 iterations)for count in range(1, 6)
: where count
starts at 1 and goes to 5 (5 iterations)for count in range(5, 0, -1)
: where count
starts at 5 and goes to 1 but explicitly states to count by -1. This instance is usually used if incrememting by more than 1 or counting backwards.The range is always one less than the end count.
For loops are also great for accumulations. So if we wanted to add the sum of the first ten numbers we could do the following:
int total;
for(int i = 1; i <=10; i++){
total += i;
}
total
is an accumulator that allows us to keep adding into it until it the count is reached.
Like decision structures, loops can be written inside other loops. These are nested loops. When we put loops in other loops we can really perform a lot of work in short lines of code. A lot of notebooks feature the multiplication tables from one to 12. We can write that using nested loops. See the coding examples below.
Language | Code | Assume all headers and functions/methods have been properly defined |
---|---|
C++ |
for(int i = 1; i <= 12; i++){
|
C# |
for(int i = 1; i <= 12; i++){
|
Java |
for(int i = 1; i <= 12; i++){
|
Python |
for i in range(1, 13):
|
We note then that the for loop written inside another for loop serves to form a nested loop. This particular piece of code will print the 144 products of numbers between 1 and 144 in little time. This demonstrates the power of loops. It is always good to be careful with using loops as they can cause a lot of nightmares if not properly handled.
Loops are quite useful for helping programmers in solving really large tasks. Over the course of your career, you will learn more about how loops can be implemented in problem solving, including controlling reading data from files, websites, and using loops to control data from collections. I believe loops and decisions are two of the most valuable programming concepts that someone new to programming can learn.