 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.

### Example

#### Calculating the average of an array of numbers

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 (Python) 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
ndata = 1000 Store the size of the data array in a variable called nData
sum = 0.0 The variable sum will accumulate the growing sum of terms in the array. It must be initialized to zero.
for n in range (0, nData): 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).
sum = sum + data[n] 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 sum += data[n]
mean = sum / nData The definition of the mean – the sum of the values divided by how many there are

### for loops ( c ) 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.

#### Zero-based indexing

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
ndata = 1000 Store the size of the data array in a variable called nData
sum = 0.0; 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.
for (n=0; n<nData; n++) { 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.
sum = sum + data[n]; 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 sum += data[n];
mean = sum / nData; The definition of the mean – the sum of the values divided by how many there are

### while loops

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.

### while loop (Python) 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.

#### while vs. for

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
x = [90.4 ...] 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.
sum = 0.0
n = 0
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 = len(x) 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.
while (n < nData) 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.
sum += x[n] 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.
n++ 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.
mean = sum / nData Calculate the mean of the numbers.

### while loop ( c ) instruction explanation
x[ ] = {90.4 ...}; 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.
float sum = 0.0;
int n = 0;
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.
nData =
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.
while (n < nData) 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.
sum += x[n]; 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.
n++; Add one to n after each run through the loop. This is what gets checked before each iteration.
mean = sum / nData; Calculate the mean of the numbers.

### while loop 2 (Python)

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
f = open( ... ); 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.
while line:; 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.'
try: ... except: ... 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.
line=float(f.readline()) 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.
x.appendline(line) This instruction appends the value in line to the list variable, x.
nData++ This instruction adds one to the variable nData, which is counting the data points in the file as they are read in.
for n in range ... Now simply calculate the average of the data as in the examples above.

### while loop 2 ( c ) instruction explanation
FILE *fp; In c we must establish a pointer to our file. It has the specific type FILE.
fp = fopen( ... ,"r");; 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 x;
float sum;
int nData = 0; int i;
Here we initialize some variables. In c, all variables must be explicitly typed as float, integer ...
while ((fscanf(fp, "%f",
&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.
fclose(fp); Closing the file flushes any memory associated with it - a good practice.
for (i=0; i<nData; i++) { This for loop prints the data and sums the values.
printf("mean=%5.3f", sum/nData); The average is calculated inside of this print statement, just before it is printed.

### Nested loops – loops inside loops

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.

### Nested loop example (Python)

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
x = [1, ..., 5];
y = [6, ..., 10];
Here we define two list variables, x and y, each containing five elements.
ny = len(x);
nx = len(y);
;
The len function allows us to conveniently determine the number of items in a list (not its length in bytes.
z = [[0 for i in range(nx)] for j in range(ny)] This strange initializer is really handy. The 0 for i in range(nx) part creates nx elements in the x direction. For each of those, the for j in range ny part creates ny additional elements.
for i in range (nx):
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.
print('{0:4d}'.format(x[i][j]),end=' ') '{0:4d}'.format is the format string. It says that the 0th element to be printed should be a four decimal-place integer (4d). (x[i][j]) is the i-jth element of the matrix to be printed. The ,end=' ' part makes sure that the last thing printed on each line is a blank space and not a newline character. We put the newline in after the inner loop using the instruction print(), which prints nothing but a newline character.

### Nested loop example ( c ) Here is the output of this program (note: the code here would have to be inserted into an int main() { . . . } function.) instruction explanation
x = [] ... nx, ny; These are array, matrix and integer declarations in c. All variables must be explicitly typed in c.
nx = sizeof(x)/sizeof(int);
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.
for (i=0; ifor (j=0; j These are the nested loops, analogous to our Python example above. Each time the outer loop increments, the full inner loop runs.

### You can help

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.