Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1371 Introduction to Computing for Engineers

Similar presentations


Presentation on theme: "CS1371 Introduction to Computing for Engineers"— Presentation transcript:

1 CS1371 Introduction to Computing for Engineers
Iteration (GAtech2004– 2011Oct.tw) 9/4/2003

2 Control Flow Statements
Learning Objectives Learn about how to control the sequence of expressions that are evaluated in a program. Topics FOR statements WHILE statements We are going to cover a lot of very important material in this lecture and slideset.

3 Problem 1: Introducing the FOR Structure
Step 1: Describe problem: Write a MatLab program to calculate the area and the circumference of TEN circles enter the radius as an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20. Step 2: Describe input and output INPUT CALCULATE OUTPUT Radius R Area Circumference This is a slightly more complicated version of Problem #1. It requires a FOR statement, but we will start by trying to use another IF statement… Step 3: Define test cases R=0  Area=0 and Circumference=0 R=1  Area= and Circumference=2 

4 Problem 1 … cont’d. Step 4: Develop the solution
Describe the algorithm: Develop the process: Calculate the area Calculate the circumference If the area is big enough, Display radius, area and circumference otherwise, display nothing Repeat 10 times START r Area = r2 Circum = 2r count=0 N = 0 IF count >= 10 True False INPUT R OUTPUT N AREA = pR2 CIRC = 2pR STOP We are following the same problem-solving process. IF AREA > 20 False True OUTPUT R. AREA. CIRC N = N + 1 count = count + 1

5 FOR loop for j=1:10 computations Repeats for specified number of times
done for j=1:10 % computations; end computations The FOR statement will solve our problem. This statement is ideal when you need to execute a loop of code a specified number of times. Repeats for specified number of times ALWAYS executes computation loop at least once!!! Can use + or – increments Can escape (BREAK) out of computational loop before normal termination would occur.

6 More Details of the FOR Loop
x=[1.1,2.6,-3.4]; for x % computations; end for j=vec computations done FOR variable can be a vector of integer or floating point values Indexing is by columns only! z=rand(4,5); for z % computations; end Matlab’s version is a bit different from C and other similar languages. The control (FOR) variable in Matlab can be a vector of values and each value is used for one execution of the loop. This can be VERY tricky. The control variable must be either a row vector or an array. Row vector: executes for each value (e.g., I = 0:2:30 will execute for I=0,2,4,…30) Array: executes for each column of the array VERY TRICKY! The Matlab FOR statement is very powerful but can be tricky to use. If the control variable is a null or NaN, no executions take place. On your own: What happens if the FOR variable is set to 0? to null (empty)? to NaN? FOR loop will execute for the 4 successive columns of z Each column of z contains a vector of 5 random values

7 Problem 1: … cont’d Step 4: Develop the solution Write Matlab code
Initialize counter START Use a FOR loop: calculate the area and the circumference of TEN circles allow the radius to be an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20. N = 0 Exit FOR FOR J = 1:10 INPUT R OUTPUT N FOR loop AREA = pR2 CIRC = 2pR STOP Now we can redesign our flowchart with a FOR loop as shown. IF AREA > 20 OUTPUT R. AREA. CIRC N = N + 1

8 Problem 2: … cont’d % calculate the area and circumference of 10 circles % print it out if the area is greater than 20 N = 0; for i = 1:10 radius = input( '\nPlease enter a radius:' ); radius = abs(radius); % make sure always is positive! area = pi * radius ^2; circumference = 2 * pi * radius; if area > 20 fprintf('\n Radius = %f units', radius); fprintf('\n Area = %f units squared', area); fprintf('\n Circumference = %f units', circumference); else N = N + 1; end fprintf('\n %f circles with area less than 20', N); Loop for i=1…10 Print only if area>20 The code is much easier to follow now! Make case for initialization of variables. Tie to defensive programming. Tie to how computer computes (if you have done this in the earlier lecture). Please encourage students to try this exercise at home. End of FOR loop

9 Handled negative radius
Problem 1 … contd. Step 5: Test the results >> basicFOR Please enter a radius:0 Please enter a radius:1 Please enter a radius:2 Please enter a radius:3 Radius = units Area = units squared Circumference = units Please enter a radius:-4 Radius = units Area = units squared Circumference = units Please enter a radius:5 Radius = units Area = units squared Circumference = units Please enter a radius:6 Radius = units Area = units squared Circumference = units Please enter a radius:7 Radius = units Area = units squared Circumference = units Please enter a radius:8 Radius = units Area = units squared Circumference = units Please enter a radius:9 Radius = units Area = units squared Circumference = units circles with area less than 20 >> Handled negative radius Testing, testing, testing…

10 Problem 2: Introducing the WHILE Structure
Step 1: State the problem: Write a MatLab program to calculate the area and the circumference of ANY NUMBER of circles so long as the radius is greater than zero take the radius as an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20. Step 2: Describe input and output INPUT CALCULATE OUTPUT How will we be able to stop the calculation process? ANSWER: we’ll stop when a zero radius is entered. Radius R Area Circumference Sometimes, we need to use a looping structure like a FOR loop but we don’t know in advance exactly how many times we will need to execute the loop. The WHILE statement is the solution. We are now extending the original problem to illustrate just such a situation. QUESTION: how can we stop this looping situation? Step 3: Define test cases R=0  Area=0 and Circumference=0 R=1  Area= and Circumference=2  Create case with 0 areas > 20 and with specified # > 20 to test

11 Problem 2 … contd. Step 4: Develop the solution
Describe the algorithm: Develop the process: Repeat until radius = 0 calculate the circumference calculate the area If the area is big enough, Display radius, area and circumference otherwise, display nothing r Area = r2 Circum = 2r Remember to plan for and include a termination condition. Otherwise your WHILE loop might continue indefinitely (control-c will stop a runaway Matlab program)

12 Problem 2: … cont’d Step 4: Develop the solution
Develop a Matlab solution START Initialize N = 0 R = 0 AREA = 0 CIRC = 0 Use a WHILE loop: calculate the area and the circumference of circles while the radius is > 0 allow the radius to be an input variable output radius, area and circumference IF the area is greater than 20 square units. output the number of circles with area  20. INPUT R Exit WHILE WHILE R > 0 OUTPUT N AREA = pR2 CIRC = 2pR STOP Tie chart symbols to code. Discuss when to use WHILE and when to use FOR statements. WHILE loop IF AREA > 20 OUTPUT R. AREA. CIRC N = N + 1 INPUT R

13 Problem 2 - Programming the WHILE Loop
% calculate the area and circumference of circles % print results if the area is greater than 20; print the % number of circules with area less than 20; terminate on area<=0 N = 0; radius = input('\nPlease enter a radius: '); while radius > 0 area = pi * radius ^2; circumference = 2 * pi * radius; if area > 20 fprintf('\n Radius = %f units', radius); fprintf('\n Area = %f units squared', area); fprintf('\n Circumference = %f units', circumference); else N = N + 1; end fprintf('\n %f circles with area less than 20', N); Loop while radius > 0 Note the need to repeat the user input here Using a zero radius value (or a negative radius) is an old trick to terminate a loop. It is crude and many more elegant solutions exist today. Sometimes it can lead to problems, especially if the negative value accidentally gets included in the problem data. While end

14 Problem 2 … contd. Step 5: Test the result Please enter a radius: 5
Radius = units Area = units squared Circumference = units Please enter a radius: 4 Radius = units Area = units squared Circumference = units Please enter a radius: 3 Radius = units Area = units squared Circumference = units Please enter a radius: 2 Please enter a radius: 1 Please enter a radius: 0 circles with area less than 20 >> Tie chart symbols to code. Discuss the “if” structure and when to use it.

15 WHILE Loop initialize k while k<10 computations change k
done k=0; while k<10 % computations; k=k+1; end computations change k Will do computational loop ONLY if WHILE condition is met Be careful to initialize WHILE variable Can loop forever if WHILE variable is not updated within loop!!!

16 Problem Solving Linear Interpolation is the process of calculating a straight line between two points and using this to compute intermediate results. If the points are close enough together, the errors can be quite small and the computations are quick and easy. Consider linear interpolation between 2 points on the X-Y plane represented as (x1, y1) and (x2, y2) Develop your own m-function to take the two points as inputs and the x value of the intermediate point to compute. Return the computed y value Test this for some data This problem can be worked in many ways. It is a good introduction to the material in Chapter 18 which highlights some of Matlab’s powerful interpolation functions.

17 Summary Topics Covered Action Items for loop statement
while loop statement Summary Action Items Review the lecture Keep exploring MATLAB! Come prepared to ask questions about MATLAB This slideset covers a lot of material. Review it carefully!


Download ppt "CS1371 Introduction to Computing for Engineers"

Similar presentations


Ads by Google