Академический Документы
Профессиональный Документы
Культура Документы
ALGORITHMS &
COMPUTING I
Thomas PEYRIN
AY 2016/17 Semester 1
19/09/16
L6-2
Loop Statements
Consider creating a table of circle areas with radii ranging
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
L6-3
Lessons Learned
19/09/16
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
19/09/16
L6-5
Can be
any vector
19/09/16
for i = 1:5
fprintf(%d\n,i)
end
action
First i is initialized to 1
L6-6
19/09/16
L6-7
and products
We want to calculate:
i 1
i 1 2 ... n
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
L6-8
performed on every
element
As for loop, we could
for i = vec
outarg = outarg + i;
end
19/09/16
L6-9
values in a vector
MATLAB has a built in function prod, that will return the
19/09/16
L6-10
Preallocating a Vector
There are two possibilities to simulate cumsum:
19/09/16
L6-11
Initialized to
empty vector
New running
sum is appended
BAD!
19/09/16
L6-12
Preallocate enough
Memory for the new
vector
Overwrite the 0s with
the running sum
Much better!
19/09/16
L6-13
to the end)
3. If any element is less than the working minimum, than that
19/09/16
L6-14
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
Preallocate
the vector
Store the value
19/09/16
L6-16
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
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
L6-18
Lessons Learned
19/09/16
L6-19
nested loop
The entire inner loop is part of the action of the outer loop
General form:
Inner
loop
Outer
loop
19/09/16
L6-20
*****
*****
*****
*****
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
L6-21
Preallocate
the matrix
19/09/16
L6-22
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
L6-23
for i = 1:col
for j = 1:row
19/09/16
L6-24
column sums:
>> sum(sum(mat))
Q: How can I find the sum of a row?
19/09/16
L6-25
*
**
***
****
19/09/16
L6-26
19/09/16
Clicker Question 2
for a=4:-1:1
for b=a:-1:2
fprintf(%i,b)
end
fprintf(\n)
end
L6-27
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
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
L6-29
Lessons Learned
19/09/16
L6-30
19/09/16
L6-31
19/09/16
L6-32
Repeat until
fac>high
19/09/16
L6-33
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
L6-34
19/09/16
L6-35
Lessons Learned
19/09/16
L6-36
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
L6-37
=> Answer:
Convert the input to integer (e.g. using int32())
Compare input with converted value
used for
comparison
19/09/16
L6-38
Lessons Learned
19/09/16
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
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