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.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
Introduction to Computing Science and Programming I
Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
Introduction to C Programming
Fall 2004ENGR 111A MatLab – Palm Chapter 4, Part 2 The if and switch structure Class 10.1 Sections: 4.4 and 4.6.
Chapter 8 and 9 Review: Logical Functions and Control Structures Introduction to MATLAB 7 Engineering 161.
Lecture 5 Review Programming Program Structures Comparison Repetition: looping or iteration Conditional execution: branching Bubble Sort.
Week 6 - Programming I So far, we’ve looked at simple programming via “scripts” = programs of sequentially evaluated commands Today, extend features to:
CIS101 Introduction to Computing Week 11. Agenda Your questions Copy and Paste Assignment Practice Test JavaScript: Functions and Selection Lesson 06,
Precedence Parentheses Arithemetic ^ * / + - (exception logical not ~ ) Relational > =
Chapter 4 MATLAB Programming Logical Structures Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Programming in Matlab Day 1: Basics. Matlab as a calculator >> 2+2 ans = 4 >> 2^3 ans = 8 >> sqrt(2) ans = Command Window Basic operations Sum:
Programming with MATLAB. Relational Operators The arithmetic operators has precedence over relational operators.
CIS101 Introduction to Computing Week 12 Spring 2004.
Week 7 - Programming II Today – more features: – Loop control – Extending if/else – Nesting of loops Debugging tools Textbook chapter 7, pages
Programming For Nuclear Engineers Lecture 12 MATLAB (3) 1.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
Chapter Seven Advanced Shell Programming. 2 Lesson A Developing a Fully Featured Program.
Chapter 4 MATLAB Programming Combining Loops and Logic Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
INTRO TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in text files.
Chapter 2 - Algorithms and Design
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
1 Introduction to Flowcharting. 2 Writing a program Defining the problem –Write down what the program will do Planning –Write down the steps, draw a flowchart.
Introduction to Engineering MATLAB – 6 Script Files - 1 Agenda Script files.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Introduction to MATLAB 7 for Engineers William J. Palm.
Input Textboxes Input Boxes Different than textboxes Good for small amount of input (form full of textboxes is not nice) X = Inputbox(“prompt message”,
CPS120: Introduction to Computer Science Decision Making in Programs.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Flowcharts and Algorithms. Review of Terms  A computer is a machine that can represent and manipulate data –Ultimately the data and the instructions.
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
Structured Programming: Debugging and Practice by the end of this class you should be able to: debug a program using echo printing debug a program using.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Review, Pseudocode, Flow Charting, and Storyboarding.
read and learn from example loop programs develop modular program
ENG College of Engineering Engineering Education Innovation Center 1 More Script Files in MATLAB Script File I/O : Chapter 4 1.Global Variables.
Chapter 4 Controlling Execution CSE Objectives Evaluate logical expressions –Boolean –Relational Change the flow of execution –Diagrams (e.g.,
Introduction to Engineering MATLAB - 13 Agenda Conditional statements  If – end  If – else – end  if – elseif – else - end.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Conditional Statements.  Quiz  Hand in your jQuery exercises from last lecture  They don't have to be 100% perfect to get full credit  They do have.
A simple classification problem Extract attributes Pattern Pattern recognition decision x C1 C2.
Files: By the end of this class you should be able to: Prepare for EXAM 1. create an ASCII file describe the nature of an ASCII text Use and describe string.
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Why Repetition? Read 8 real numbers and compute their average REAL X1, X2, X3, X4, X5, X6, X7, X8 REAL SUM, AVG READ *, X1, X2, X3, X4, X5, X6, X7, X8.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
1 Structured Programming EEN170 Programming in MATLAB.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
INTRODUCTION TO PROGRAMMING Chapter 2. M-files While commands can be entered directly to the command window, MATLAB also allows you to put commands in.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
EEE 161 Applied Electromagnetics
REPETITION CONTROL STRUCTURE
Matlab Training Session 4: Control, Flow and Functions
Programming Mehdi Bukhari.
MATLAB: Structures and File I/O
Selection CIS 40 – Introduction to Programming in Python
MatLab – Palm Chapter 4, Part 2 The if and switch structure
MatLab – Palm Chapter 4, Part 2 The if and switch structure
Chapter 3: Selection Structures: Making Decisions
Chapter 3: Selection Structures: Making Decisions
Selection Statements Chapter 3.
Matlab Basics.
REPETITION Why Repetition?
Presentation transcript:

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

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

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)

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

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

You cannot use radical in MATLAB, use sqrt(x) or x.^0.5 Tests in Command Window >> test(2) ans = >> 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

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

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

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

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 = 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.

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

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?

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

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

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

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 = 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.

Example flowchart for if-elseif-else structure

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

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 = 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.

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

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.

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

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.

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

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

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)

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

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

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.

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