University of Alaska Fairbanks
Geophysical Institute

Beyond the Mouse - The geoscientist's computational chest.

4. Fundamental Programming Principles II -- Control Flow

"Programming is legitimate and necessary academic endeavor."
Donald E. Knuth

How do we change the flow of a program based on certain conditions? Every (see: esolang) Usually a higher level programming language comes with constructs to evaluate conditions, repeat things until a certain condition is met, or repeat a statements list x times. This lecture contains basic logic [sic!], and definitions for flow control constructs in formal, Matlab, and C-Shell language.

Lecture

Fundamental Principles 2 (pdf)

Examples

This lecture contains many examples: tar.gz or zip archive. Work through them! Change things! Breaks things and try to fix them. Get dirty, you geoscientists!

Exercises:

4.0

Download examples and run the Matlab scripts -- play with them.

4.1

Using Matlab, write a function sum_of_even_squares that calculates the sum of squares of all even numbers between 2 and N. 'N' is a parameter of this function that should be greater than 2 (you have to make sure that this is true, users are generally evil!). Send me the .m file that contains the solution.
Hints: the shortest version is with a for-loop; but you may use while and if combinations as well. Before you enter any loop, assign a useful value to the returned variable (which you define in the function header). Then you can add the intermediate results (squared even numbers) at each step to this variable.

Solution: sum_of_even_squares.m

4.2

Write a Matlab script (or function) that implements this flow chart: fun_function.

You will probably realize that this is an abstract version of the outer loop for our class. We'll fill in the details next week in class. So far, I only want you to take the step from something abstract that's written out on paper to executable code. That's hard enough. There is no specific way I want you to do this. You may use whichever constructs from class seem suitable for the job. I do want this very flow chart implemented, though (No changes in upper limits or initialization values, etc.; feel free to deliver prettier output, though). On this note, be aware of N> being initialized with the value 1. Depending on your current implementation of the function sum_of_even_squares this may lead to trouble (Although 4.1, told you to foresee this :). To avoid this trouble, improve the function sum_of_even_squares by including conditions that avoid infinite loops and return a correct result (the sum of even squares from 2 to 1 is still zero). Feel free to add comments to the code; even if it seems silly since there's not gonna be much code.

Solution: fun_function.m

ronni <at> gi <dot> alaska <dot> edu | last changed: Oct 01, 2009