gibson:teaching:fall-2014:math445:lecture9-diary

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.

A `for`

loop repeats a given action a fixed number of times. The general form of a `for`

loop is

for value = vector action end

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.

for n = 1:10 fprintf('The value of n is %i\n', n); end

**example 2:** Print the numbers from 10 to 0.

for n = 10:-1:0 fprintf('%i '); end fprintf('blast off!\n');

**example 3:** Write a `mysum`

function that computes the sum of the elements of a vector.

function s = mysum(x) % return the sum of the components of vector x s = 0; % start with partial sum s = 0 for i = 1:length(x) % loop over all elements in x s = s + x(i); % add x(i) to the previously computed partial sum end end

**example 4:** Write a function that computes the factorial of *n*.

function p = factorial(n) % return the factorial of n (assume n is a positive integer) p = 1; % start with partial product p = 1 for k = 1:n % loop k over all integers from 1 to n p = p*k; % multiply previous partial product by k end end

**The for loop is probably the single most important programming construct in numerical mathematics.**

A `while`

loop repeats a given action as long as its condition is true. The general form is

while condition action end

In order for the `while`

loop to terminate, the action must modify variables in the condition.
For example, the factorial function above could also be written this way…

gibson/teaching/fall-2014/math445/lecture9-diary.txt · Last modified: 2014/10/15 12:45 by gibson