# Loops¶

Both *for* loops and *while* loops are indispensable tools for programming in
Matlab (or any other programming language)

*For* Loops¶

The big idea behind a *for* loop is that it executes a set of commands a
predetermined amount of times

### Question¶

Suppose you want to create a series that starts with the base number 10. You then want to add 2 to the base number 5 different times and you want the addition to be cumulative. Finally, you want to know what the cumulative value is after the third and fourth iteration.

Note: obviously you can do this in your head, the point is to simplify the problem enough to avoid obfuscating the basic idea of the for loop.

- The first thing we need to do is choose names for all of the numbers involved
in the computation. This allows us to easily change values later without having
to rewrite the whole program. Let’s call the base number
*base*, the amount we want to add by*add*, and how many iterations we want*iter*. Next we need to create a vector that stores all of our computed values, which we can call*results*.

- A useful approach to creating a results vector is by using the
*ones*function and multiplying it by*NaN*. This gives you a vector full of NaN’s (not a number). Some people use the*zeros*function to create a matrix of zeros instead. The reason that this is a suboptimal approach is that many times in applications the calculated value will be zero. This makes it hard to debug your program because you won’t know if the answer is zero or the program had an error and no calculations were made.

- The results vector will need to be one element longer than the number of
iterations, otherwise you will have a
*fence post problem*. Fence post problems occur when for loops either over or under calculate by one iteration. This occurs because we will store the base value in the first index of the results vector.

- The first line of a for loop is the word
*for*and a variable that will change value after every loop, followed by the range of values the variable will take. In our example we choose*i = 1:5*. This means that the variable i will start as the number 1, increase by the integer 1 every loop, and complete its final loop once*i=5*.

- The body of the loop is the set of commands that will be executed everytime
the loop iterates. In our example, we take advantage of the variable i changing
and use it to step through each value of the results vector. The loop stops
executing commands and iterates to the next loop when it reaches the word
*end*. Also, the body should be indented by one tab relative to for and end.

- Finally, we want to know what the value is after 3 and 4 iterations. One
approach is to double click on the results variable in the
*workspace*. Another more useful approach (consider you want to know the value after 5256 iterations) is to have the computer display the answer for you. You will often want more than one answer displayed so it is useful to have the computer tell you in words what numbers it is printing. In our example, we display the numbers both individually and together.

- It is important to notice that we choose output from the index of the results vector as the iteration we are interested in plus 1 to account for our initial value being stored in the first index.

- Enter your code in a new script as shown below

- Click
*save*and name the file*forloop1*. You can now run the program by either clicking the*run*button from the editor menu or by typing “forloop1” in the command window followed by enter.

- The output is displayed in the command window and you can see all of the program variables in the workspace

- Now, if you want to know what the cumulative sum is after 5256 iterations, simply change iter to 5256 and the results to results(5256+1). The answer displayed is 10,522

*While* Loops¶

The big idea behind a *while* loop is that before entering the loop, a logical
statement is considered. If the logical statement is true, the body of the
loop is executed. If the logical statement is false, the loop is terminated
and no commands are executed. The while loop is used to loop until some logical
statement becomes false.

### Question¶

Suppose you would like to know how many times the number 1,000,000 can be divided by 3 while remaining larger than 1?

- To answer this question we can let a while loop divide 1,000,000 by 3 until the result is less than 1 and let the computer count how many times the loop is executed. Once the loop is complete, we can subtract 1 from our loop count, and that will be the answer we are looking for. The reason we subtract 1 is because in order for the test to be false, the quotient must be less than 1, which means we have exceeded our threshold. Subtracting 1 from the count implies that the previous quotient will be greater than one, and will be our smallest quotient greater than 1.

- Open a new script. Let’s choose some names for the values involved in solving
this problem. Let
*start*be our starting value of 1,000,000. Let*test*equal start, but it will be a variable that changes throughout the process. We can also let*div*be the number we wish to divide by and let*count*keep track of how many times we enter the loop.

- To start the while loop you type “while” followed by a logical expression
that you would like to test every time before entering the loop. We want to
test that the variable named
*test*is greater than 1 before entering. Next, type the commands you want to be executed every time the loop is entered. In this case we want to add 1 to count, create a temporary variable that is the quotient of our test variable divided by 3, and update our test variable to the quotient. The last two steps can be completed as one, but we leave them seperate to improve exposition. As always, close the loop body with*end*.

- Here is one way of writing the program

- And here is the output from the above program