

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


ย Previous Lecture: ย Iteration using for ย Todayโs Lecture: ย Iteration using while ย Review loops, conditionals using graphics ย Announcements: ย Section in classrooms, not lab, this week ย Project 2 due Monday, 9/ ย Prelim 1 on Sept 25 at 7:30pm. Email [email protected] if you have a conflict ย We do not use break in this course ย Register your clicker!
September 16, 2008 Lecture 6 3
Example: n -gon ร circle
Inscribed hexagon ( n /2) sin(2 ฯ / n )
Circumscribed hexagon n tan( ฯ / n ) Asn approaches infinity, the inscribed and circumscribed areas approach the area of a circle. How big shouldn be?
September 16, 2008 Lecture 6 4
Find n such that outerA and innerA converge First, itemize the tasks:
September 16, 2008 Lecture 6 5
Find n such that outerA and innerA converge Now organize the tasks ร algorithm:
n gets initial value Repeat until tolerance is reached: calculate innerA, outerA for current n diff= outerA โ innerA increase n
% Convergence of inner and outer areas of regular n-gons on unit circle fprintf('\n n\t A(n)\t B(n)\n'); % Initialize n, innerA, and outerA n= 3; innerA= 3sqrt(3)/4; outerA= 3sqrt(3); tol= 0.01; % convergence tolerance % Compute and print areas until convergence while (outerA - innerA > tol) fprintf('%4d %9.6f %9.6f \n', n, innerA, outerA); n= n+1; innerA = (n/2)sin(2pi/n); outerA = n*sin(pi/n)/cos(pi/n); end fprintf('%4d %9.6f %9.6f \n', n, innerA, outerA);
September 16, 2008 Lecture 6 9
Can we replace the initialization of innerA and outerA with the following?
innerA= (n/2)sin(2pi/n); outerA= n*sin(pi/n)/cos(pi/n); innerA=2; outerA=4; Both A and B would work Neither A nor B would work
September 16, 2008 Lecture 6 11
Common loop patterns Do somethingn times
for k= 1:n % Do something
end
Do something an indefinite number of times %Initialize loop variables
while ( not stopping signal ) % Do something
% Update loop variables end
September 16, 2008 Lecture 6 15
Pattern to do something n times
for k= 1:1:n % Do something
end
Do something an indefinite number of times %Initialize loop variables k= 1; while ( k <= n ) % Do something
% Update loop variables k= k+1; end
September 16, 2008 Lecture 6 16
In Matlab, which claim is true? (without break)
for-loop can do anything while-loop can do while-loop can do anything for-loop can do for- and while-loops can do the same things
September 16, 2008 Lecture 6 18
for-loop or while-loop: that is the question
ย for-loop: loop body repeats a fixed (predetermined) number of times. The โincrementโ is fixed.
ย while-loop: loop body repeats an indefinite number of times under the control of the โloop condition.โ
% drawDemo close all figure axis equal off hold on
DrawRect(0,0,2,2,'k') DrawDisk(1,1,1,'m') DrawStar(1,1,1,'y')
hold off
Example: Nested Stars