Presentation is loading. Please wait.

Presentation is loading. Please wait.

Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.

Similar presentations


Presentation on theme: "Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement."— Presentation transcript:

1 Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement use “else” statements use “elseif” statements Text: Section 4.4

2 Review Exercise: Temperature Data Analysis Get into groups of 3 (2 if necessary) Download  FWTemperature.txt from the class website This file contains the daily high and low temperatures at FWA Row 1  Day of the Month Row 2  Highs for March 2007Row 3  Lows for March 2007 Row 4  Highs for April 2007Row 5  Lows for April 2007 Develop and execute a script to: load in this file Determine and display the number of days in each month where the highs were 60 degrees or higher. Determine and display the number of days in each month where the highs were between 50 and 60 degrees

3 Matlab script file % FWTemp.m % Elizabeth A. Thompson, Ph.D. % October 22, 2008 clear S=load('FWTemperature.txt'); % row 1 is day of month % row 2 is highs for March 2007 % row 3 is lows for March 2007 % row 4 is highs for April 2007 % row 5 is lows for April 2007 % Determine and display number of days in Mar 2007 when highs >=60 disp('Number of days in 03/07 when highs were >= 60 degrees:') sum(S(2,:)>=60) disp('Number of days in 04/07 when highs were >= 60 degrees:') sum(S(4,:)>=60) disp('Number of days in 03/07 when highs were between 50 and 60 degrees:') sum(S(2,:)>50 & S(2,:)<60) disp('Number of days in 04/07 when highs were between 50 and 60 degrees:') sum(S(4,:)>50 & S(2,:)<60)

4 Start MATLAB and set up this function template m-file (test.m) function y = test(x) % This is a function template set up as % convenient way to test program structures. % y = test(x) % your nameMarch 2008

5 If statement If x is greater than or equal to zero then y equals the square root of x if x >= 0 y = x^0.5; end Add these lines to your test.m file and try it out with several inputs e.g. x = 2, x = 0, x = -2

6 You cannot use radical in MATLAB, use sqrt(x) or x.^0.5 Tests in Command Window >> test(2) ans = 1.4142 >> test(0) ans = 0 >> test(-2) Try a vector x = [2, 0, -2] >> test([2, 0, -2]) >> Nothing happens: When test a logical vector in an if statement all cases must be true for the if to go to the true command statements. Try assigning an output to the last case: >> y = test(-2) ??? Output argument "y" (and maybe others) not assigned during call to "C:\Documents and Settings\Administrator\My Documents\MATLAB\test.m (test)". Error in ==> test at 7 if x >= 0 You get an error because for a negative number no value is assigned to the output. We will look at how to fix this with the next program See Conditional Statements 1 Handout

7 Example Flowchart for this simple if code block Diamonds = conditional branch points Rectangles = executable statements

8 Flow Charts of Conditionals Conditionals (e.g. if statements) are represented by diamonds: Input comes in the top A question or conditional statement is in the diamond Two lines leave - one for yes (true), one for no (false) One diamond may feed another No (False) Yes (True) Input value question/ conditional

9 If/else statements If x is greater than or equal to zero then y equals the square root of x or else display an error & set y to NaN if x >= 0 y = sqrt(x); else disp(‘Error: input is negative’) y = NaN; end

10 Add this else error message to your test.m file and try Repeat earlier test cases with this new addition to the m- file in MATLAB: >> test(2), test(0), test(-2) ans = 1.4142 ans = 0 ERROR: Input is Negative ans = NaN Note: NaN is a special MATLAB code for “not a number.” This code makes sure the output of the function has something in it so errors are not encountered in future use.

11 Parallelograms = Input/Output Steps Example Flowchart for this if-else structure

12 Example Function: eng2PL1.m Download eng2PL1.m from class website This function takes a one word input (in quotes) Try it with several words including >> eng2PL1(‘banana’) >> eng2PL1(‘orange’) What does it do that our last translator did not do? Look at the code - How does it work?

13 eng2PL1.m function x = eng2PL1(x) % Lots o’ Comments % make all letters lower case and set up list of vowels & consonants x = lower(x); if any(x(1) == 'aeiouy') % if x starts in a vowel simply add 'ay' x = [x, 'ay’]; else % otherwise move leading consonant to the end of the word and add 'ay' x = [x(2:end), x(1), 'ay']; end

14 If / elseif / else If x is greater than zero then y equals the square root of x or else if y is equal to zero then display “x = 0” & set y to zero or else display “input is negative” & set y to NaN

15 if x > 0 y = x^0.5; elseif x == 0 disp(‘input is zero’) y = 0; else disp(‘ERROR: input is negative’) y = NaN; end MATLAB Example: Modify your test.m code to match

16 Add this elseif segment (& change the first condition) in your test.m file. Repeat earlier test cases in MATLAB: >> test(2), test(0), test(-2) ans = 1.4142 input is zero ans = 0 ERROR: Input is Negative ans = NaN What happens if you only put one equal sign in the else if statement? >> test(2), test(0), test(-2) ??? Error: File: test.m Line: 9 Column: 10 The expression to the left of the equals sign is not a valid target for an assignment. It attempts to do an assignment, which is not legal here.

17 Example flowchart for if-elseif-else structure

18 Nested if: alternative logic for the previous example if x>=0 if x==0 disp(‘input is zero’) y = 0; else y = sqrt(x); end else disp(‘ERROR input is negative’) y = NaN end This “inner if” is only executed if the “outer if” is true

19 Revise your earlier file to follow this nested if structure. Repeat earlier test cases with this new addition to the m- file in MATLAB: >> test(2), test(0), test(-2) ans = 1.4142 ans = 0 ERROR: Input is Negative ans = NaN This type of nesting can be done in either the “true” section of the if statement (as shown here) or it can be done in the “false” section of the if statement where it would be executed only when the “outer” if is false.

20 Example Flowchart for this nested if structure Again notice this “inner if” is only executed if the “outer if” is true

21 Leap Year Exercise: In groups of 2 or 3 arrange the cards to form a flow chart for the leap year rules. Diamonds represent conditions, Rectangles results. The rules: 1.All years evenly divisible by 400 are leap years 2.All years evenly divisible by 100 are not leap years (except when condition 1 is met), 3.Years divisible by 4 but not by 100 are leap years (in addition to condition 1), 4.All other years are not leap years.

22 Is year divisible by 400? Yes No Is year divisible by 100? Is year divisible by 4? No Leap Year Not a Leap Year Leap Year Yes

23 Another helpful function mod(numerator, denominator) try for: 12, 3 11, 3 10, 3 9, 3 Can you see what it does? How could this be used to determine if a year is evenly divisible by 4. Create a function that will determine if a given year is a leap year or not.

24 Matlab code function y=leapyear(ye) % Function to determine if ye is a leapyear % Input ye--year that we would like to determine if it is a leapyear % Output y--logical T(1)(Is leap year) or F(0)(Is not leap year) if mod(ye,4)==0 y=logical(1); elseif mod(ye,100)==0 y=logical(0); elseif mod(ye,4)==0; y=logical(1); else y=logical(0); end if y==1 disp('Leap year') else disp('Not a leap year') end

25 Practice Problem Write a function that accepts a score from 1-100 and then returns a letter grade based on a usual 10% curve (90-100 = A, 80-90=B, 70-90 = C …). Inputs and outputs should happen on the command line. Goal Input Output Calc. Variations Try using elseifs Try using nested ifs

26 Practice Problem set in pairs work on table on next page with class have work in pairs on program Goal Develop a function that will determine letter grade from % score on a standard 10% curve InputScore % OutputGrade Letter Calc.89  B 90  ? 76  C 66  D 55  F (test all branches)

27 function Grade = Curve(score) % function Grade=Curve(score) % Determines the letter grade given % a % score based on a 10%/grade % Palm problem 4-17 if score >=60 Grade = 'D' if score >= 70 Grade = 'C' if score >= 80 Grade = 'B' if score >=90 Grade ='A' end else Grade ='F' end Solution function 1 using nested if statements, nested in the “true” portion of each loop. Notice: 1.The grade is not simply displayed but saved to a variable and then returned on the command line so it can be stored in the main program. 2.Leaving off semicolons does allow the output to be displayed as well

28 function Grade = Curve(score) % function Grade=Curve(score) % Determines the letter grade given % a % score based on a 10%/grade % Palm problem 4-17 if score >=60 Grade = 'D' if score >= 70 Grade = 'C' end if score >= 80 Grade = 'B' end if score >=90 Grade ='A' end else Grade ='F' end Solution function 2 using sequential if nested in an outer if statement. Introductory comments in all of these examples are abbreviated for these notes. Full comments should include the call form, all variables, author and date

29 function Grade = Curve(score) % function Grade=Curve(score) % Determines the letter grade given % a % score based on a 10%/grade % Palm problem 4-17 if score >= 90 Grade = 'A‘; else if score >= 80 Grade = 'B'; else if score >= 70 Grade = 'C'; else if score >=60 Grade ='D'; else Grade ='F'; end Solution function 3 using nested if in the “false” segment (i.e., after the else statement). notice: in this example I chose to use semicolons to suppress the echo print.

30 function Grade = Curve(score) % function Grade=Curve(score) % Determines the letter grade given % a % score based on a 10%/grade % Palm problem 4-17 if score >= 90 Grade = 'A' elseif score >= 80 Grade = 'B' elseif score >= 70 Grade = 'C' elseif score >=60 Grade = 'D' else Grade = 'F' end Solution function 4 Using the else if structure throughout


Download ppt "Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement."

Similar presentations


Ads by Google