Upload
lorin-fletcher
View
218
Download
3
Tags:
Embed Size (px)
Citation preview
Overview
Writing programs that can repeat operations
for loops
while loops
Reference: Text book Ch 4.
A Motivating Example
Recall the robot_vision_simulator?
It could calculate the service of one cadet, based on their uniform colour.
What if we want a robot to monitor its surroundings or act repeatedly for some period of time…?
Loops
Computer programs can repeat operations using loops
This saves the programmer (you!) from writing out the same code multiple times
Many programming languages have two or three types of loops. MATLAB has two:
for loops while loops
Example: Data Processing
% loop to print 10 numbers and their squares
for x=1:10
x_squared = x*x;
fprintf(‘%d squared is %d\n’, x, x_squared);
end
Nested Loops
% code to print all the times-tables from% the 1-times-table up to the 12-times-table
for x=1:12 % repeat for each times-table
fprintf(‘\nThe %d-times-table:\n’, x); fprintf(‘-------------------\n’);
for y=1:12 % repeat for each entry in table x_times_y = x*y;
fprintf(‘%d times %d is %d\n’, x, y, x_times_y); endend
Beware! Time Complexity
Often want to optimse the time it takes code to run
For one loop the time complexity is equal to the number n of iterations (repetitions) of the loop
Written O(n)
In a nested loop the time complexity is number of iterations of the first loop multiplied by the number of iterations of the nested loop:
Eg: O(n2) This gets really slow if:
n is large there many levels of nesting
Syntax: for Loops
for ( counter_variable = range )code to be repeated goes here
end
Programmer or function user know the range to use a for loop
Overview: while Loops
“Used when you don’t know how many repetitions are required,
but
you know some condition about when to stop repeating.”
Problem Solving With while Loops
The bouncing height of a ball is determined by its starting height and elasticity:
ht+1 = ht x elasticity2
Where elasticity is between 0 and 1.
How many times will the ball bounce between given starting and stopping heights?
From Problem to Program…
1. Understand the problem ‘in English’
2. Develop a rough solution on paper
3. Implement the solution in MATLAB
4. Test your solution
Beware! The Infinite Loop
while true
fprintf(‘This is a never ending loop\n’);
end
Beware! You could end up with an infinite loop without such an obvious condition
This blatant example is the basis of a simple computer virus or denial of service attack