Вы находитесь на странице: 1из 40

MH 1401

ALGORITHMS &
COMPUTING I
Thomas PEYRIN
AY 2016/17 Semester 1

19.09.2016 Lecture 6: Loop Statements

19/09/16

Lecture 6: Loop Statements

L6-2

Loop Statements
Consider creating a table of circle areas with radii ranging

from 0.1cm to 100cm in steps of 0.05cm


Looping statements, or loops, allow to repeat

statements
The statements that are repeated are called the action of

a loop
There are two basic types of loops
Counted loops
Conditional loops

19/09/16

Lecture 6: Loop Statements

L6-3

MH 1401 Algorithms & Computing I


Outline
for loops
Nested for loops
while loops
Error Checking

Lessons Learned

19/09/16

Lecture 6: Loop Statements

L6-4

Counted Loop
A counted loop repeats statements a specified number of

times
It is known ahead of time how many iterations are

required
Example: repeat these statements 10 times

-> use a for loop

19/09/16

Lecture 6: Loop Statements

L6-5

The for Loop


Iterator
variable

Can be
any vector

for loopvar = range


action
end
It is common to use i,j,(k,l,..) for iterator variables

This overrides the value of the built-in variables i,j for 1


The range can be specified using any vector
Usually the colon operator : is used for the range

19/09/16

Lecture 6: Loop Statements

The for Loop (ctd)

for i = 1:5
fprintf(%d\n,i)
end

action

First i is initialized to 1

Then the action of the loop is executed


Then i is incremented
At the end i has the value 5

L6-6

19/09/16

L6-7

Lecture 6: Loop Statements

The for Loop (ctd)


Example: finding sums

and products
We want to calculate:

i 1

i 1 2 ... n

A running sum keeps

changing as we keep
adding to it

function runsum =
% sum1ToN returns
% integers from 1
% Format of call:

sum1ToN(n)
the sum of
to n
sum1ToN(n)

runsum = 0;
for i = 1:n
runsum = runsum + i;
end
end

Initialization to 0
running sum

19/09/16

Lecture 6: Loop Statements

L6-8

Sums and Products for Vectors


Frequently it is required to

calculate sums and/or the


product of the elements of
a vector
Values in a vector typically

represent the same thing


Same operation can be

performed on every
element
As for loop, we could

have also used:

function outarg = myvecsum(vec)


% myvecsum returns the sum of
%
the elements in a vector
% Format of call:
%
myvecsum(vector)
outarg = 0;
for i = 1:length(vec)
outarg = outarg + vec(i);
end
end

for i = vec
outarg = outarg + i;
end

19/09/16

Lecture 6: Loop Statements

L6-9

Sums and Products for Vectors (ctd)


MATLAB has a built in function sum, that will sum all

values in a vector
MATLAB has a built in function prod, that will return the

product of all values in a vector


cumsum, calculates the cumulated sum of a vector
cumprod, calculates the cumulated product of a vector

cumsum and cumprod, return a vector with the same

dimension as the input vector

19/09/16

Lecture 6: Loop Statements

L6-10

Preallocating a Vector
There are two possibilities to simulate cumsum:

Variant 1: Start with an empty vector and concatenate


each running sum value
Variant 2: Preallocate the vector to the correct size, then
change the value of each element to be successive
running sums

19/09/16

L6-11

Lecture 6: Loop Statements

Preallocating a Vector (ctd)


Variant 1 is not very efficient:
Every time the vector is extended a new chunk of memory

must be found that is large enough for the new vector


Then all values are copied to the new location
function outvec = myveccumsum(vec)
% myveccumsum simulates cumsum for a vector
% Format: myveccumsum(vector)
outvec = [];
runsum = 0;
for i = 1:length(vec)
runsum = runsum + vec(i);
outvec = [outvec runsum];
end
end

Initialized to
empty vector
New running
sum is appended

BAD!

19/09/16

Lecture 6: Loop Statements

L6-12

Preallocating a Vector (ctd)


Variant 2 is much better

function outvec = myveccumsumii(vec)


% myveccumsumii imitates cumsum for a vector
% It preallocates the output vector
% Format: myveccumsumii(vector)
outvec = zeros(size(vec));
runsum = 0;
for i = 1:length(vec)
runsum = runsum + vec(i);
outvec(i) = runsum;
end
end

Preallocate enough
Memory for the new
vector
Overwrite the 0s with
the running sum

Much better!

19/09/16

Lecture 6: Loop Statements

L6-13

Combining for Loops with if Statements


Example: find the minimum (or maximum) value in a vector
Algorithm (input: vector, output: min of the vector):

1. The working minimum (the minimum that has been found

so far) is the first element in the vector to begin with


2. Loop through the rest of the vector (from the 2nd element

to the end)
3. If any element is less than the working minimum, than that

element is the new minimum

19/09/16

L6-14

Lecture 6: Loop Statements

Preallocating a Vector (ctd)


function outmin = myminvec(vec)
% myminvec returns the minimum
%
value in a vector
% Format: myminvec(vector)
outmin = vec(1);
for i = 2:length(vec)
if vec(i) < outmin
outmin = vec(i);
end
end
end

Assign the first

element to be the
working minimum
< is sufficient rather
than <=
if is sufficient rather
than if-else
MATLAB has built in
functions min and
max that find the
minimum and the
maximum values in a
vector

19/09/16

L6-15

Lecture 6: Loop Statements

Input in a For Loop


A function that prompts the user n times to enter a

number and stores these numbers in a vector


function numvec = forinputvec(n)
% forinputvec returns a vector of lenght n
% It Prompts the user and puts n numbers
%
into a vector
% Format: forinputvec(n)
numvec = zeros(1,n);
for iv = 1:n
inputnum = input('Enter a number: ');
numvec(iv) = inputnum;
end
end

Preallocate
the vector
Store the value

19/09/16

L6-16

Lecture 6: Loop Statements

Clicker Question 1
What would be the result of the following for loop?
for i=4:2:8
fprintf(a )
end
25%

25%

25%

25%

A. a a a
f

B. a a a a a a a a a a a a a a
f

C. a a a a a a a a
f

D. a a a a

aa
aaaaaaaa
A.

B.

C.

D.

19/09/16

Lecture 6: Loop Statements

Clicker Question
What would be the result of the following for loop?
for i=4:2:8
fprintf(a )
end
A. a a a
f

B. a a a a a a a a a a a a a a
f

C. a a a a a a a a
f

D. a a a a

aa
aaaaaaaa

L6-17

19/09/16

Lecture 6: Loop Statements

L6-18

MH 1401 Algorithms & Computing I


Outline
for loops
Nested for loops
while loops
Error Checking

Lessons Learned

19/09/16

L6-19

Lecture 6: Loop Statements

Nested For Loops


The action of a loop can be any valid statement
When the action of a loop is another loop, this is called a

nested loop
The entire inner loop is part of the action of the outer loop
General form:

for loopvarone = rangeone


for loopvartwo = rangetwo
action2
end
end

Inner
loop

Outer
loop

19/09/16

L6-20

Lecture 6: Loop Statements

Nested For Loops (ctd)


Example: Printing a box

of stars (*) depending on


the users input
Algorithm:

for every row of output:


Print the required number of

stars (using an inner loop)


Move the cursor down to
the next line

*****
*****
*****
*****

function printstars(rows,columns)
% Prints a box of stars
% How many will be specified
%
by 2 variables for the number
%
of rows and columns
% loop over the rows
for i=1:rows
% for every row loop to print *'s
%
and then one \n
for j=1:columns
fprintf('*')
end
fprintf('\n')
end
end

19/09/16

Lecture 6: Loop Statements

L6-21

Nested For Loops (ctd)


Example: creating a multiplication table
function outmat = multtable(rows, columns)
% multtable returns a matrix which is a
% multiplication table
% Format: multtable(nRows, nColumns)
% Preallocate the matrix
outmat = zeros(rows,columns);
for i = 1:rows
for j = 1:columns
outmat(i,j) = i * j;
end
end
end

Preallocate
the matrix

Use for loops,


because rows
and columns
are known

19/09/16

Lecture 6: Loop Statements

L6-22

Nested For Loops (ctd)


Example: calculate the overall sum of the elements of a

matrix
Algorithm (input: matrix, output: the sum):
Use size to determine the number of rows and columns
Initialize the running sum
Use nested loop
Loop over rows (i)
Loop over columns (j)
Add each element to running sum

19/09/16

Lecture 6: Loop Statements

L6-23

Nested For Loops (ctd)


function outsum = mymatsum(mat)
% mymatsum returns the overall sum
%
of the elements in a matrix
% Format: mymatsum(matrix)
[row col] = size(mat);
outsum = 0;
% The outer loop is over the rows
for i = 1:row
for j = 1:col
outsum = outsum + mat(i,j);
end
end
end

for i = 1:col
for j = 1:row

The order of the


loops does not
matter in this example

19/09/16

Lecture 6: Loop Statements

L6-24

Nested For Loops (ctd)


Recall MATLAB has a built in function sum, that operates

columnwise on a matrix, i.e. it will return the sum of a


column
Overall sum can be calculated by just summing the

column sums:
>> sum(sum(mat))
Q: How can I find the sum of a row?

=> simply use the sum on the transposed matrix:


>> sum(mat)
cumsum, min, max, operate columnwise

19/09/16

Lecture 6: Loop Statements

Nested For Loops (ctd)


Q: how to print a triangle of stars, like this:
% Prints a triangle of stars
% How many will be specified by rows
rows = 4;
% The outer loop is over the rows
for i = 1:rows
for j = 1:i
fprintf(*)
end
fprintf(\n)
end

L6-25

*
**
***
****

Inner loop iterates


only up to the
value of i

19/09/16

Lecture 6: Loop Statements

L6-26

Nested For Loops (ctd)


Q: we would like to load experimental data from a file and obtain the
sum of the values in each row, except for negative numbers (which
are considered as experiment errors)
% Sums only positive numbers from file.
% Reads from the file into a matrix and then calculates and
% prints the sum of only the positive numbers in each row
load datavals.dat;
[r c] = size(datavals);
for i = 1:r
sumrow=0;
for j = 1:c
if datavals(i,j) >= 0
sumrow = sumrow + datavals(i,j);
end
end
fprintf(The sum for row %d is %d\n,i,sumrow)
end

19/09/16

Clicker Question 2

for a=4:-1:1
for b=a:-1:2
fprintf(%i,b)
end
fprintf(\n)
end

What would be the result of the


following nested for loop?
A.

L6-27

Lecture 6: Loop Statements

4444
333
22
f

B.

4444
333
22
1

25%

25%

25%

25%

C.

432
32
2
f
hy

D.

4321
321
21
1

A.

B.

C.

D.

19/09/16

Clicker Question 2
What would be the result of the
following nested for loop?
A.

L6-28

Lecture 6: Loop Statements

4444
333
22

for a=4:-1:1
for b=a:-1:2
fprintf(%i ,b)
end
fprintf(\n)
end

B.

4444
333
22
1
f

C.

432
32
2
g
f

D.

4321
321
21
1

Equivalent to:
for a = [4 3 2 1]
for b = [a 2]
fprintf(%i ,b)
end
fprintf(\n)
end

19/09/16

Lecture 6: Loop Statements

L6-29

MH 1401 Algorithms & Computing I


Outline
for loops
Nested for loops
while loops
Error Checking

Lessons Learned

19/09/16

Lecture 6: Loop Statements

L6-30

The while Loop


while condition
action
end
The action is executed as long as the condition is true
First the condition is evaluated
If true the action is executed
Condition is evaluated again and again and again
Q: How does it stop?

=> Something in the action has to change something in


the condition to become false! Otherwise you have an
infinite loop (press Ctrl+C to stop if this situation happens)

19/09/16

Lecture 6: Loop Statements

L6-31

The while Loop (ctd)


Example: Find the first factorial that is greater than the

input argument high


Note: previously we could use a for loop, because we

only wanted to calculate a particular factorial. That is, it


was known ahead of time how many times we need to
repeat that loop. This is not the case here.
Algorithm (input: high, output: the 1st factorial > high):
One variable iterates through the values 1,2,3,
One variable stores the factorial of the iterator at each step
If factorial is not greater than high, increase the iterator

19/09/16

Lecture 6: Loop Statements

L6-32

The while Loop (ctd)


function facgt = factgthigh(high)
% factgthigh returns the first
%
factorial > high
% Format:
%
factgthigh(inputInteger)
i=0;
fac=1;
while fac <= high
i=i+1;
fac = fac * i;
end
facgt = fac;
end

i can also be initialized to 1


The execution statement

Repeat until
fac>high

has to be rewritten then


It is possible to use more

complicated conditions for


the while loop using ||
and the && operators

19/09/16

Lecture 6: Loop Statements

L6-33

Input in a while Loop


while loops can be used to process input from the user as

long as the user is entering correct data


First prompt is outside the loop
Subsequent prompts are within the loop so there is a new

value to be checked
What happens if the user enters -23? => it goes out of the loop
inputnum = input('Enter a positive number: ');
while inputnum >= 0
fprintf('You entered a %d.\n\n',inputnum)
inputnum = input('Enter a positive number: ');
end
fprintf('OK I stop!\n')

19/09/16

Lecture 6: Loop Statements

L6-34

Counting in a while Loop


while loops are frequently used to count how many

times the action was repeated


counter=0;
inputnum=input('Enter a positive number: ');
while inputnum >= 0
fprintf('You entered a %d.\n\n',inputnum)
counter = counter + 1;
inputnum = input('Enter a positive number: ');
end
fprintf('You entered %d positive numbers.\n',counter)

19/09/16

Lecture 6: Loop Statements

L6-35

MH 1401 Algorithms & Computing I


Outline
for loops
Nested for loops
while loops
Error Checking

Lessons Learned

19/09/16

Lecture 6: Loop Statements

L6-36

Error-Checking User Input in a while Loop


Usually there is a valid range of values
If a user enters incorrect value, the program should repeat

the prompt until the value is in correct range


Very common application of a conditional loop, called

error-checking
inputnum=input('Enter a positive number: ');
while inputnum < 0
inputnum = input('Invalid! Enter a positive number: ');
end
fprintf('Thanks, you entered a %.1f \n',inputnum)

19/09/16

Lecture 6: Loop Statements

L6-37

Error-Checking for Integers


MATLAB uses by default double
Question: How to check if the user has entered an integer?

=> Answer:
Convert the input to integer (e.g. using int32())
Compare input with converted value

If equal, an integer has been entered, otherwise not

inputnum = input('Enter an integer: ');


num2 = int32(inputnum);
while num2 ~= inputnum
inputnum = input('Invalid! Enter an integer: ');
num2 = int32(inputnum);
end
fprintf('Thanks, you entered a %d \n',inputnum)

used for
comparison

19/09/16

Lecture 6: Loop Statements

L6-38

MH 1401 Algorithms & Computing I


Outline
for loops
Nested for loops
while loops
Error Checking

Lessons Learned

19/09/16

Lecture 6: Loop Statements

L6-39

Lessons learned
Common Pitfalls:
Forgetting to initialize a running sum or count variable to 0
Forgetting to initialize a running product variable to 1
Initialization might be required again in the inside loops in case

of nested loops
In cases where loops are necessary, not realizing that if an

action is required for every row in a matrix, the outer loop must
be over the rows (analog for columns)
Not realizing that the action of a while loop might never be

executed
Failing to error-check the input into a program

19/09/16

Lecture 6: Loop Statements

L6-40

Lessons learned
Programming Style Guidelines:
Use loops for repetition only when necessary:
for statements as counted loops
while statements as conditional loop
Do not use i or j as iterator variable names if the use of the built

in constants i and j is desired (otherwise ok)


Indent the action of loops
If the loop variable is just being used to specify how many

times the action of the loop is to be executed (i.e. do n times),


use the colon operator 1:n

Preallocate vectors and matrices whenever possible (when the

size is known ahead of time)

Вам также может понравиться