Iteration

Often when we are writing code, we want to the program to repeat (or iterate) the same or a similar action many times. For example, suppose we wish to sum the odd integers from 1 to 9. We could do this in Matlab using the following code:

sum = 0;
sum = sum + 1;
sum = sum + 3;
sum = sum + 5;
sum = sum + 7;
sum = sum + 9

Of course we could have done this in one line of Matlab code:

sum = 1 + 3 + 5 + 7 + 9

Suppose we want to sum the odd integers from 1 to 1,000,001. Neither of our previous strategies for doing this would be very practical. And the situation can even be "worse": suppose we want to sum the odd integers from 1 to N where N is some number that will be given to us later. We can't even write out all the code to do this since we don't know how many numbers we will be adding!

The way to handle these kinds of situations, where we want to perform some set of steps over and over and over is to use iterative programming structures known as repetition statements, or loops. We will look at two kinds of loops in particular, while loops and for loops.

In Matlab, the while loop has the structure:

    initialize condition variable(s)
    while condition is true
        do these statements  % body of while loop
        update condition variable(s)
    end

If we know for which values our loop needs to execute it is best to write the loop as a for loop. In Matlab, the for loop has the structure :

    for k = [ list of values of k to be used in the loop ]
        do statements for current value of k  % body of for loop
    end

If we know exactly how many times the loop is going to execute, it is also easier to write it as a for loop. Just replace the vector list with the colon operator to create a vector with the correct count of loop iterations.

    for k = first : increment : last
        do these statements for each value of k  % body of for loop
    end

You will learn more about the details of each of these loop structures in the next lessons.