CS 211 Lesson 7
Repetition: while Loops
Quote:
Try not to become a man of success but rather try to become a man of values. Albert Einstein
Lesson Objectives:
Understand the purpose of loops
Know the syntax of the while loop
Understand the initialization, testing, and modification sections of a loop
Know what types of problems require a while loop
Be able to use the while loop to solve problems
Lesson :
I. MATLAB Concepts
A. Loops in general
Loops, like branches, are control structures common to most programming languages.
The purpose of loops is to repeatedly execute a series of statements.
Executing the same series of statements repeatedly does not necessarily mean performing exactly the same actions because the statements inside loops typically contain variables which may have different values for each repetition of the loop.
There are two primary classifications of loops:
condition-controlled loops
Repeat one or more statements while some condition is true.
In general, when the loop begins, you do not know how many times it will repeat.
A condition-controlled loop in MATLAB is called a while loop.
count-controlled loops
Repeat one or more statements for a fixed number of times.
In general, when the loop begins, you know how many times it will repeat.
A count-controlled loop in MATLAB is called a for loop.
B. while loops
The while loop has the following format (syntax):
while <logical expression>
<one or more statements>
end
For example:
Y = [];
X = 0; % initialize loop control variable (X)
while X <= 100 % test loop control variable
Y(end+1) = X^2;
X = X + 1; % modify loop control variable
end
The while loop behaves as follows:
When execution reaches the while, the logical expression is evaluated. If the logical expression evaluates to false, then execution skips to the code immediately following the end. If the logical expression evaluates to true, the code immediately after the expression and before the end (i.e., the loop body) is executed. After the loop body is executed, execution returns back to the beginning of the while loop and the logical expression is re-evaluated. The body of the loop will execute repeatedly until the logical expression evaluates to false.
It is important to indent the code in the loop body to make the repeated code stand out (MATLAB's smart indent will do this for you).
The body of the loop may execute zero, one, or many times.
A loop that never stops repeating (until the program halts) is called an infinite loop.
The logical expression for most while loops includes a variable called the loop control variable.
Most loops have a single loop control variable, but it is possible to have more than one loop control variable.
All, non-infinite loops must satisfy the following three conditions:
The loop control variable must be initialized before the loop begins (before the while line).
The loop control variable must be tested each iteration of the loop (in the while loop's logical expression).
The loop control variable must be modified in the body of the loop (so that the loop will eventually stop).
The mnemonic ITM (initialize, test, modify) is useful for remembering these three loop requirements.
Leaving out any of these three steps can cause problems, such as an unintended infinite loop.
If you have an executing program in an infinite loop, terminate the program by making the command window active and typing CTRL-C.
C. Input validation
A common use for while loops is input validation .
An input validation loop repeatedly prompts for and gets a value from the user until the user enters a valid value.
The example below validates that the input age is non-negative
Age = input('Enter the patient''s age in years: '); % initialize Age
while Age < 0 % test Age
disp('INVALID INPUT - the age cannot be negative!')
Age = input('Please re-enter the patient''s age in years: '); % modify Age
end
A variation of the previous example is shown below. This code does not duplicate the input statement, but it requires that the test (Age < 0) be done twice.
Age = -1; % initialize Age
while Age < 0 % test Age
Age = input('Enter the patient''s age in years: '); % modify Age
if (Age < 0)
disp('INVALID INPUT - the age cannot be negative!')
end
end
D. Counting and while loops
Count-controlled loops can be implemented with while loops.
For example, the following while loop displays the integers from 1 to 10 -- the loop body always executes 10 times.
Count = 1; % initialize Count
while Count <= 10 % test Count
disp(Count)
Count = Count + 1; % modify Count
end
Please note however that this loop is best encoded as a for loop which you will learn about in the next lesson.
E. An example
The following code computes the square root of a number using the "successive approximation method":
Error_tolerance = 0.00001;
New_guess = 1;
N = input('Enter a positive number: ');
Old_guess = N;
while abs(New_guess - Old_guess) > Error_tolerance
Old_guess = New_guess;
New_guess = (Old_guess + N/Old_guess)/2;
end
fprintf('The square root of %f is approximately %f.\n', N, New_guess)
A while loop is appropriate for this task since the number of iterations required to find the square root varies with the size of the number.
Make sure you can identify the ITM (initialize, test, modify) components of this loop.
II. Good Programming Practices
Vertical alignment of statements makes code easier to understand (readable) and easier to modify.
Vertically align, in the same column, corresponding while and end keywords, indenting all statements inside them to the right at least 2 spaces.
You can use MATLAB's smart indent feature (Text ->
Smart Indent or
Ctrl-I) to automatically indent selected code for you.
Use a while statement when you need to repeat a block of code, but the exact number of times to repeat the code is not known until run-time.
III. Algorithms
Find a root of an equation using the Newton-Raphson method.
Given an equation, we often need to find the locations where
the equation, if plotted, crosses the X axis. Said another way, we need to
find the values for X that cause the function to evaluate to zero (i.e.,
where f(x) = 0).
The Newton-Raphson method finds roots of an equation by starting with a "guess" of where a
root value might be. It then refines this "guess" using the tangent of the
curve to select a new "guess." This is repeated over and over
until the guess "closes in on" a root value. The method works for
many types of equations but can sometimes fail if there are no root value
close to the initial guess or if the equation has no real roots.
The
following explanation of the Newton-Raphson method refers to the figure below.
We know that the slope of the tangent line at any point along a curve is
defined as the "change in Y" divided by the "change in X". Therefore, the
tangent to a curve can be written as:
f'(xi)
= (f(xi)-0) / (xi - xi+1)
The value xi in the above figure
is our "guess" for the location of the root. If we can calculate the derivative
of the equation, then the only unknown value in the tangent
equation is xi+1. Solving for
this unknown in the tangent equation results in the formula:
xi+1 = xi -
f(xi) / f'(xi)
Notice that the point xi+1
is closer to the root than our original "guess". If we use this new point as
our "guess" and apply the equation over several iterations, we will get
potentially get closer and closer to the actual root value.
In MATLAB, code to perform the Newton-Raphson root finding algorithm might look like:
Tolerance = 10e-10; X = input('Please enter your best guess where a root might be : '); while abs(f(X)) > Tolerance X = X - f(X)/f_derivative(X); end fprintf('Root: f(%0.15f) = %0.15f\n', X, f(X));
Lab Work: Lab 7
References: Chapman Textbook: section 4.1