Looping is one of the most powerful techniques used in computer programming. It takes full advantage of the blinding speed of computer processors to do the same tasks thousands or millions of times in a row.
In this section we'll learn about a few kinds of looping structures and how to implement them in both Python and c++ . In the examples that follow, I'll write the Python code on the left and equivalent c or c++ code on the right.
You will need to know something about array variables (also called list variables), and how to access their elements in order to understand this example.
Goal: Read through a large array or list of numbers (in this example there are 1000 of them), add each value to a growing sum, and when the end of the array is reached, divide that sum by the number of elements to obtain the average.
In both examples, we'll assume that we've already created an array called data[ ] (or x[ ] in some examples), and populated it with at least 1000 numerical values.
for loops are structures generally used when we know precisely how many times we want to do some iterative task. In this case it's nData times. Other looping structures we'll look at below allow us to loop only until a certain condition, like the end of an array or list, is met.
What's not shown here: the data in the array x[ ] are not shown. They would have to be declared (see examples below) or read in from a file (also illustrated below).
instruction | explanation |
---|---|
Store the size of the data array in a variable called nData | |
The variable sum will accumulate the growing sum of terms in the array. It must be initialized to zero. | |
n is a counting variable. It ranges from 0 to one less than nData in steps of one. The colon ( : ) indicates that all indented steps below this statement will be evaluated, in turn, each time the loop is executed (nData times). | |
The value of the next point in the data array, data[n] is added to what is currently stored in the variable sum and reassigned to that memory location. One could also write |
|
The definition of the mean – the sum of the values divided by how many there are |
for loops are structures generally used when we know precisely how many times we want to do some iterative task. In this case it's nData times. Other looping structures we'll look at below allow us to loop only until a certain condition, like the end of an array or list, is met.
Arrays and lists in c and Python (and most computer languages) are indexed beginning at zero. If an array contains n elements, the indices of those elements run from 0 to n-1.
instruction | explanation |
---|---|
Store the size of the data array in a variable called nData | |
The variable sum will accumulate the growing sum of terms in the array. It must be initialized to zero. Don't forget to end statements with ; in c. | |
n is a counting variable. It begins at n=0 and can have integer values less than nData. Each time the loop is run, the index n is incremented by one afterward ( n++ ). Statements between the braces { } are executed each the loop runs. | |
The value of the next point in the data array, data[n] is added to what is currently stored in the variable sum and reassigned to that memory location. One could also write |
|
The definition of the mean – the sum of the values divided by how many there are |
Sometimes we need to loop through a set of instructions several times, but we don't always know exactly how many. That's a good situation for a while loop. Each time a while loop runs it evaluates a condition to see if it's finished yet. That condition can be almost anything, such as an indication from the operating system that the end of a file has been reached.
Carrying on with our number-averaging example from above, say we'd like to calculate the average of an array of numbers, no matter how many numbers are in the array. Here are a couple of examples of how we might use a while loop.
This loop could also be implemented as a for loop. Below we'll do another while loop that would be more difficult to implement using a for loop.
for loops are generally used when the number of iterations is known. It's bad form to jump out of a for loop prematurely on some test. while loops run until some condition is met, and that condition can be dependent on any number of other factors in the program. Once a while loop's stop condition has been met, the program jumps out of the loop and executes the next instructions.
instruction | explanation |
---|---|
This is a list declaration in Python. It other languages such a structure is usually called an array. The computer establishes an address for the first element, then each element contains another address that points to the memory location of the next element, and so on. | |
The variable sum will accumulate the growing sum of terms in the array. n will be our loop counter. Both must be initialized to zero. | |
nData is the number of elements in the x list. the built-in function len() gives us the number of elements in the list. Because we ask for the length of the list, we are free to add or remove elements from it and the code will still run just fine. | |
This is the head of the loop. It says that as long as n is less than nData, the program should keep running the indented instructions below this statement. This loop will run for n = 0, 1, 2, ... up to one less than nData. | |
This is our growing sum. It starts at zero, and on each run through the loop, the nth element of the list x is added to it, and the new value is re-stored in sum. | |
This instruction adds one to n, incrementing the loop after the main command (above) has been executed. Once the end of the indented instructions have been followed, the computer will re-evaluate the while statement to see if it should continue of if it's done. | |
Calculate the mean of the numbers. |
instruction | explanation |
---|---|
This is an array declaration in c. The computer establishes an address for the first element, then each element contains another address that points to the memory location of the next element, and so on. | |
The floating-point variable sum will accumulate the growing sum of terms in the array. The integer n will be our loop counter. Both must be initialized to zero. | |
sizeof(x) / sizeof(float); |
nData is the number of elements in the x list. In c, the built in operator len returns the length of a variable or array in bytes. If we want the number of elements in the array, we have to divide by the number of bytes in each element, in this case floating-point numbers. |
This is the head of the loop. It's analogous in every way to the while loop in Python. Don't forget the { } in c. | |
This is our growing sum. It starts at zero, and on each run through the loop, the nth element of the array x is added to it. | |
Add one to n after each run through the loop. This is what gets checked before each iteration. | |
Calculate the mean of the numbers. |
In these examples, we'll use a while loop to read a file of unknown length (number of entries) to the end, and then average the values using a for loop. Don't worry if the file-handling instructions are foreign to you. They exist just to open a file and allow the program to read it line-by-line.
instruction | explanation |
---|---|
This instruction opens the file in quotes, then assigns the variable f to point to it. f is then the file object, and has a number of useful properties and associated methods or functions, like f.readline(), which reads the next line of the file into memory. | |
line is a variable used as a logical or boolean variable. Any non-zero value of line means 'True,' while line = 0 means 'False.' The loop keeps running as long as line = 'True.' | |
These optional instructions are used to handle errors. We never know about the structure of a file and we need to plan for trouble. The try instruction tries to read a line from the file. If it's successful, the program continues to run as planned. If not, the except switch is thrown and the loop terminates via the break command. | |
f.readline( ) reads the next line of the file. The function float( ) converts it to a floating-point number, and the result is assigned to line. As long as line ≠ 0, the loop will continue to run. | |
This instruction appends the value in line to the list variable, x. | |
This instruction adds one to the variable nData, which is counting the data points in the file as they are read in. | |
Now simply calculate the average of the data as in the examples above. |
instruction | explanation |
---|---|
In c we must establish a pointer to our file. It has the specific type FILE. | |
The pointer is attached to the file when it is opened by the built-in function fopen. "r" means "read-only." We won't be writing to this file. | |
float sum; int nData = 0; int i; |
Here we initialize some variables. In c, all variables must be explicitly typed as float, integer ... |
&x[nData]))!=EOF) { |
fscanf is a built-in function that reads formatted text. The format code %f means "read one floating point number per line." That datum is stored in the array x. The address operator, &, is required in scanf; it needs the address of the variable into which the read-in value will be stored. If the end of the file is reached, the value returned by fscanf(...) is NULL, our signal to end the while loop. Inside the loop, nData is incremented by one each time through. |
Closing the file flushes any memory associated with it - a good practice. | |
This for loop prints the data and sums the values. | |
The average is calculated inside of this print statement, just before it is printed. |
We can also run loops inside of other loops. For example, we might want to (do something a number of times) a number of times. The example below will show how to fill out and print the rows and columns of a matrix using one loop inside of the other.
We can also run loops inside of other loops. For example, we might want to (do something a number of times) a number of times. The example below will show how to fill out and print the rows and columns of a matrix using one loop inside of the other.
Note that the number of operations inside a nested loop can get quite large. If your outer loop runs from 1-1000 and so does the inner loop, then the number of calculations run inside the nested loop is 1000 × 1000 = a million. Three or more nested loops means even more operations performed. Be careful: You can easily get yourself into a position in which you're trying to execute so many instructions that your program will take forever!
instruction | explanation |
---|---|
y = [6, ..., 10]; |
Here we define two list variables, x and y, each containing five elements. |
nx = len(y); |
The len function allows us to conveniently determine the number of items in a list (not its length in bytes. |
This strange initializer is really handy. The |
|
for j in range (ny): |
These are the nested loops. We loop over the variable i from 0 to nx, and upon each iteration, we then loop over j from 0 to ny. The result is running the instructions in the inner loop nx × ny times. In the next set of nested loops we simply print each element. |
' |
Here is the output of this program (note: the code here would have to be inserted into an int main() { . . . } function.)
instruction | explanation |
---|---|
These are array, matrix and integer declarations in c. All variables must be explicitly typed in c. | |
ny = sizeof(y)sizeof(int); |
In c, the sizeof operator (it's an operator, not a function) gives the size of a variable in bytes. Dividing by the length of the type of variable (int in this case) gives the number of elements in the array. |
These are the nested loops, analogous to our Python example above. Each time the outer loop increments, the full inner loop runs. |
This site is a one-person operation. If you can manage it, I'd appreciate anything you could give to help defray the cost of keeping up the domain name, server, search service and my time.
xaktly.com by Dr. Jeff Cruzan is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. © 2016, Jeff Cruzan. All text and images on this website not specifically attributed to another source were created by me and I reserve all rights as to their use. Any opinions expressed on this website are entirely mine, and do not necessarily reflect the views of any of my employers. Please feel free to send any questions or comments to jeff.cruzan@verizon.net.