**This is an old revision of the document!** ----
====== Math 445 lecture 9: for and while loops ====== Today's main topic is //loop// constructions. Loops perform a given action repeatedly. There are two main flavors of loops: the ''for'' loop and the ''while'' loop. ===== for loops ===== A ''for'' loop repeats a given action a fixed number of times. The general form of a ''for'' loop is <code matlab> for value = vector action end </code> The ''action'' will be performed ''length(vector)'' times, with ''value'' set to each element of ''vector'' successively. It's probably clearer to see this by example. **example 1:** Print the numbers from 1 to 10. <code matlab> for n = 1:10 fprintf('The value of n is %i\n', n); end </code> **example 2:** Print the numbers from 10 to 0. <code matlab> for n = 10:-1:0 fprintf('%i '); end fprintf('blast off!'); </code> **example 3:** Write a ''mysum'' function that computes the sum of the elements of a vector. **example 4:** Write a function that computes the factorial of //n//. **The for loop is probably the single most important programming construct in numerical mathematics.** ===== while loops ===== A ''while'' loop repeats a given action as long as its condition is true. The general form is <code matlab> while condition action end </code>