“operators” (i.e. “symbols”)

74
“Operators” (i.e. “symbols”) 1. Overview: Specific Symbols that Represent Specific Actions 2. Arithmetic 3. Relational 4. Boolean 5. Output values 1

Upload: donnel

Post on 22-Feb-2016

32 views

Category:

Documents


0 download

DESCRIPTION

“Operators” (i.e. “symbols”). Overview: Specific Symbols that Represent Specific Actions Arithmetic Relational Boolean Output values. Overview: most Operators. There are 3 primary groups of operators One programming operator is very different from its use in math: . Overview, cont. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: “Operators” (i.e. “symbols”)

1

“Operators” (i.e. “symbols”)

1. Overview: Specific Symbols that Represent Specific Actions2. Arithmetic3. Relational4. Boolean5. Output values

Page 2: “Operators” (i.e. “symbols”)

Overview: most Operators

1. ARITHMETIC

+ Addition- Subtraction* Multiplication/,\ Division^ Exponentiation,

i.e. “To the power of”

• There are 3 primary groups of operators

One programming operator is very different from its use in math:

2

2. RELATIONAL

< strictly less than> strictly greater than<= less than or equal to>= greater than or equal to== is equal to~= is not equal to

3. BOOLEAN

&& “AND”|| “OR”~ “NOT”

= “the assignment operator”

Page 3: “Operators” (i.e. “symbols”)

Overview, cont.

• Operators work on operands.

3

4 * 5operands Multiplication operator

-5operand

Negative operator

Binary OperatorRequires two operands to work

Unary OperatorRequires one operand to work

Page 4: “Operators” (i.e. “symbols”)

Overview, cont.

• There are 2 types of operands:1. Numerical 1, 3.5, -472. Logical true, false

Arithmetic (+, -, /, *, ^, =) and relational (<, <=, >, >= ,==, ~=) operators work with numerical operands

4

kineticEnergy = 1 / 2 * mass * vel ^ 2

Assign operator: “place one or more values into memory”Arithmetic operators

Numerical Operands

Page 5: “Operators” (i.e. “symbols”)

Overview, cont.

• There are 2 types of operands:1. Numerical 1, 3.5, -472. Logical true, false

• Boolean (&&,||,~) operators work on logical operands

“ if this is true and this is false… do something”

5

if (it's raining outside) and (you have an umbrella)go, you won't get wet

elsestay inside!

end

Page 6: “Operators” (i.e. “symbols”)

True, False, 1, and 0?!

TrueFalse

10

Page 7: “Operators” (i.e. “symbols”)

3. Relational Operators

• Relational operators allow a comparison to be evaluated. Is thrust_a greater than thrust_b? True / False

Is surface1 equal to surface2? True / False?

Is load1 less than or equal to load2? True / False?

• Examples:

7

thrust_a > thrust_b Is thrust_a strictly greater than thrust_b?

radius <=0 Is radius negative or zero?nb_attempts<= 3 Is the number of attempts less than or equal to 3?

3 >= nb_attempts Is 3 greater than or equal to the number of attempts?

value ~= 2 Is value not equal to 2?

Page 8: “Operators” (i.e. “symbols”)

Relational Operators, cont.

• ***COMPARISON*** ==y == 5 % “Does y hold the value 5?”

% “Is y equal to 5?”• Example:menuChosen == 1 % did user choose menu #1 ?

8

Page 9: “Operators” (i.e. “symbols”)

Relational Operators, cont.

• ***COMPARISON*** ==y == 5 % “Does y hold the value 5?”

% “Is y equal to 5?”• Example:menuChosen == 1 % did user choose menu #1 ?

• Assignment = % A numerical operatory = 5; % “Store the value 5 in the

% variable y”9

Note that == and = are DIFFERENT!

Page 10: “Operators” (i.e. “symbols”)

Spaces or not?

• When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER

10

Page 11: “Operators” (i.e. “symbols”)

Spaces or not?

• When one relational operator is made up of 2 symbols (<=, >=, ~=, ==): KEEP THEM GLUED TOGETHER

• Regardless of which operator is used, a space can be used before and/or after. All these are identical to MATLAB:– thrustA<=thrustB %no spaces anywhere– thrustA <=thrustB %1 space before the operator– thrustA<= thrustB %1 space after the operator– thrustA <= thrustB %1 space before AND after

11

Page 12: “Operators” (i.e. “symbols”)

Scalars versus Vectors

• MOST of the time, you'll want to use relational operators with scalar values, but you can use them with vectors (and matrices).

• Operations follow similar rules to math on vectors, except everything is “element-by-element”

• Example:

Page 13: “Operators” (i.e. “symbols”)

Any and All

• Two functions may be helpful:any () True if ANY of the items in the vector are trueall() True if ALL of the items in the vector are true

Page 14: “Operators” (i.e. “symbols”)

4. Boolean Operators

• These operators take logical scalar values and perform some operation on them to yield a logical value

• Two Boolean operators allow to COMBINE relational expressions&& Logical AND|| Logical OR

• One Boolean operator allows to NEGATE the result~ Logical NOT“Negates”: turns true values into false, and false values into true

14

Page 15: “Operators” (i.e. “symbols”)

Boolean Operator #1: && “logical and”

• Two & symbols (“Ampersand”), glued together&&

• Both relational expressions must be true for the combined expression to be true

• X && Y yields true if and only if both X and Y are truee.g. (3 < 5) && (8 >= 8) ?(x < 1) && (x > 5) ?

x = 52.1;(5.5 < x) && (x < 100.2) ?

15

Page 16: “Operators” (i.e. “symbols”)

&&, continued

• Use of parenthesise.g.

(3<5) && (8>=8) true same as 3<5 && 8>=8 true

(x<3) && (x>5) falsesame as x<3 && x>5 false

16

For sanity, at least use spaces before/after the operator!

Page 17: “Operators” (i.e. “symbols”)

True/False

(2 > 3) && (3 < 29.3)A. True B. False C. Impossible to determine

(22 > 3) && (3 > 29.3)

D. True E. FalseF. Impossible to determine

(22 > x) && (x > 29.3)A. TrueB. False C. Impossible to determine

(x<2) && (y>0)D. True E. False F. Impossible to determine

17

• What is the result of the following statement?

Page 18: “Operators” (i.e. “symbols”)

True/False

F && TA. True B. False

T && FC. True D. False

F && FA. True B. False

T && TC. True D. False

18

• In other words, there are 4 options:

Page 19: “Operators” (i.e. “symbols”)

Boolean Operator #2: || “logical or”

• Two | (“pipe”) symbols, glued together||

• At least ONE relational expressions must be true for the combined expression to be true

• X || Y yields true if either X or Y (or both) are true

e.g. (3<5) || (5>=8) ?

x = 4.2;(x< 3) || (x > 5) ?

19

Page 20: “Operators” (i.e. “symbols”)

True/False

(2 > 3) || (3 < 29.3)A. True B. False C. Impossible to determine

(22 > 3) || (3 > 29.3)

D. True E. False F. Impossible to determine

(22 > x) || (x > 29.3)A. True B. False C. Impossible to determine

(x<2) || (y>0)D. True E. False F. Impossible to determine

20

• What is the result of the following statement?

Page 21: “Operators” (i.e. “symbols”)

True/False

F || TA. True B. False

T || FC. True D. False

F || FA. True B. False

T || TC. True D. False

21

• Again, there are 4 options:

Page 22: “Operators” (i.e. “symbols”)

Priorities between Boolean Operators

• Which operator has priority in the following?1 + 1 + 0 * 1

• Just like * has priority over + , && has priority over ||

– What is the result of this statement?x = 44.5;y = 55; (x<=50) || (0<y) && (y<40) ? ((x<=50) || (0<y)) && (y<40) ? (x<=50) || ((0<y) && (y<40)) ?

22

Page 23: “Operators” (i.e. “symbols”)

Boolean Operator #3: NOT

• One ~ symbol (“tilde”)

• “NOT” : negates a value• Example:

x = true; %keyword is known to MATLABy = ~x; %y now has the value false

• Example: The value y entered by the user should NOT be between 4 and 9 cm, inclusive:% Suppose the user enters 7.4 as a value for y~(4<=y && y<=9) ?

23

Page 24: “Operators” (i.e. “symbols”)

5. Operators: Result values

Type Operand type Result type

Arithmetic: Numbers Numberse.g. 5 * 3 15

Relational: Numbers Logicale.g. 5 < 3 false

Boolean: Logical Logicale.g. ~true false

true & false

24

Page 25: “Operators” (i.e. “symbols”)

25

Order of Operations

Operator Priority

Parenthesis () Highest

Exponentiation ^

Unary: -, NOT ~

Multiplication/division: * / \

Addition/subtraction: + -

Relational: <, <=, >, >=, ==, ~=

AND: &&

OR: ||

Assignment: = Lowest

Page 26: “Operators” (i.e. “symbols”)

Key Ideas

• Vocabulary: operators, operands, arithmetic, relational, boolean, unary, binary, numerical, logical

• Assignment vs. “is equal to” operator• Find the &, |, and ~ symbols on the keyboard• When does a && b && c evaluate to True?• When does a || b || c evaluate to True?• When does a && b || c && d evaluate to True?• Order of operations is respected when MATLAB executes any

expression

26

Page 27: “Operators” (i.e. “symbols”)

27

Conditionals

1. General Concept2. Skipping Lines of code3. The if statement4. Examples

Page 28: “Operators” (i.e. “symbols”)

28

Raising the Bar

• Up until now, every line of code would run sequentially.• All of programming comes down to only 3 things.

– Sequential Statements (EVERYTHING we have done so far)– Decision (Conditional) Structures (today)– Looping Structures (Thursday)

• The learning curve is really going to increase now.– Show up!– Submit something!– Ask for help!

Page 29: “Operators” (i.e. “symbols”)

1. General Concept of Conditionals

“CHOOSING” – This week• You may want to execute some part of code under certain

circumstances only• You may want to skip some part of a code

“LOOPING” – Starting Thursday• You may want to repeat a section of code until a new

circumstance happens• You may want to repeat a section of code for a certain

number of times

29

Page 30: “Operators” (i.e. “symbols”)

General Concept, cont.

• All conditional and loop syntax use BOOLEAN LOGIC to decide whether to skip/loop specific code-block.

• Review– Values: true, false– Relational operators: <, <=, >, >=, ==, ~=– Logical (Boolean) operators: &&, ||, ~

30

Page 31: “Operators” (i.e. “symbols”)

31

Example 1 Quadratic Equation

• Problem: Solve the Quadratic Equation

ax2 + bx + c = 0

• Theory:– Discriminant: D = b2-4ac– If D = 0, x1=x2=-b/2a

– If D > 0, x1= -b+sqrt(D)/2a, x2= -b-sqrt(D)/2a– If D < 0, no real roots

How can MATLAB only run one of those options?

Page 32: “Operators” (i.e. “symbols”)

32

2. Skipping lines of code

if switch

• TWO constructs can skip lines in MATLAB:

Page 33: “Operators” (i.e. “symbols”)

33

3. if statement

if / elseif / elseExecute statements if condition is true

Syntaxif expression statementselseif expression statementselse statementsend

ONLY these lines are necessary.

The others are optional if the problem requires them.

Page 34: “Operators” (i.e. “symbols”)

3. if statement

if <logical expression 1><code block 1>

elseif <logical expression 2><code block 2>

.

.

.elseif <logical expression n>

<code block n>else

<default code block>end

34

MATLAB uses the

keywords to know

where/what to skip.

If placed in the wrong spot, MATLAB skips to the wrong spot.

Page 35: “Operators” (i.e. “symbols”)

35

3. if statement

• Common misconception:– MATLAB skips to the “end of the code” - ABSOLUTELY NOT!– MATLAB skips to the “end” keyword and continues executing

the code (if any!)- ABSOLUTELY

Page 36: “Operators” (i.e. “symbols”)

36

Good Practice

• It's a common mistake to forget the end statement.

• It's a good practice to write the if (or switch or for or while) statement, then write the end statement, THEN write the contents that go inside the control structure.

Page 37: “Operators” (i.e. “symbols”)

Example1: weekend? weekday?

clcclear

% ask user for dayday = input('What day number is it (1-7)? ');

% find which type of day it isif day == 7 %saturdaystate = 'weekend';

elseif day == 1 %sundaystate = 'weekend';

else %any other daystate = 'weekday';

end

fprintf('That day is a %s\n', state);

37

Notice else does not have a condition. It is the default!

As far as MATLAB's concerned, day wasn't a 1 or a 7, so the else statement(s) need to run.

MATLAB goes in order: top to bottom

Page 38: “Operators” (i.e. “symbols”)

Improve it..

• Using the OR idea, simplify this if/elseif/else to a simple if/else.

% ask user for dayday = input('What day number is it (1-7)? ');

% find which day it isif day == 7 %saturdaystate = 'weekend';

elseif day == 1 %sundaystate = 'weekend';

else %any other daystate = 'weekday';

end

fprintf('That day is a %s\n', state);

38

When the same code appears under two different if conditions:"something's wrong".

Page 39: “Operators” (i.e. “symbols”)

Using Logical OR

% ask user for dayday = input('What day number is it (1-7)? ');

% find which day it isif day == 7 || day == 1 %Saturday or Sunday

state = 'weekend';else %any other day

state = 'weekday';end

fprintf('That day is a %s\n', state);

39

% find which day it isif day == 7 || 1 %Saturday or Sunday

state = 'weekend';else %any other day

state = 'weekday';end

DO NOT TRY TO SHORTCUT

Page 40: “Operators” (i.e. “symbols”)

Example2: Grade Letter

%choose letter gradeif grade >=90

letter = 'A';elseif grade >=80

letter = 'B';elseif grade >=70

letter = 'C';elseif grade >=60

letter = 'D';else

letter = 'FAIL';end

40

Value of grade Letter grade

90≤ grade A

80≤ grade < 90 B

70≤ grade <80 C

60≤ grade < 70 D

grade < 60 Fail

Page 41: “Operators” (i.e. “symbols”)

41

Example2: Grade Letter

• There is an order

%choose letter gradeif grade >=90

letter = 'A';elseif grade >=80

letter = 'B';elseif grade >=70

letter = 'C';elseif grade >=60

letter = 'D';else

letter = 'FAIL';end

90807060

Page 42: “Operators” (i.e. “symbols”)

42

Example2: Grade Letter

• There is an order

%choose letter gradeif grade >=90

letter = 'A';elseif grade >=80

letter = 'B';elseif grade >=70

letter = 'C';elseif grade >=60

letter = 'D';else

letter = 'FAIL';end

90807060

else means that the above condition was not true.

Hence it eliminates the 90 and above.

Page 43: “Operators” (i.e. “symbols”)

43

Example2: Grade Letter

• There is an order

%choose letter gradeif grade >=90

letter = 'A';elseif grade >=80

letter = 'B';elseif grade >=70

letter = 'C';elseif grade >=60

letter = 'D';else

letter = 'FAIL';end

90807060

Page 44: “Operators” (i.e. “symbols”)

44

Example2: Grade Letter

• There is an order

%choose letter gradeif grade >=90

letter = 'A';elseif grade >=80

letter = 'B';elseif grade >=70

letter = 'C';elseif grade >=60

letter = 'D';else

letter = 'FAIL';end

90807060

else means that the above conditionS were false.

Hence it eliminates the 80 and above.

And so on…

Page 45: “Operators” (i.e. “symbols”)

45

if statements within each other?

• It is absolutely possible to put a new if statement within another.

• Just remember, EACH if statement needs the end keyword that finishes it.

• This is referred as NESTED statements. (We'll talk a little more about these on Thursday).

Page 46: “Operators” (i.e. “symbols”)

46

Indentation is important

• It is part of the conventions of programming– “The body of an if, an elseif, or an else is indented”.– “programmers indent to better convey the structure of their programs

to human readers.” (Wikipedia: http://en.wikipedia.org/wiki/Indent_style )– Some languages (Python being the most well known) REQUIRE you to

have proper indentation• It also makes the code easy to read and “skip”• In MATLAB, using the following will Auto-Indent!

– It works if ALL your keywords if/end are present.

Page 47: “Operators” (i.e. “symbols”)

47

Key Ideas

• Conditionals in programming allow to SKIP (or not skip) lines of code.

• They allow the programmer to control the flow. – MATLAB's goal is to go from the 1st line to the last line.

• if statements: if and end are mandatoryelseif if there are more conditions to check after the 1st oneselse the last keyword: “for EVERYTHING else”

Keyword Number Required

if Exactly 1

elseif 0 or more (up to infinity)

else 0 or 1 (None or One)

end Exactly 1

Page 48: “Operators” (i.e. “symbols”)

48

STOP!

• Some errors, MATLAB will catch.

• MOST OF THESE, however, MATLAB will not. It will apply basic logic of true/false, and proceed.

The operations MATLAB performs will NOT be the ones they appear to be.

Page 49: “Operators” (i.e. “symbols”)

SHORTCUTS never work

%if months are jan,mar,may,jul,aug,oct,decif month==1 || 3 || 5 || 7 || 8 || 10 || 12

nb_days = 31;elseif month == 2 %February

nb_days = 29; % for leap years…else %every other months

nb_days = 30;end

49

DOES NOT WORK

AS EXPECTED

Instead, rewrite each condition separately!if month==1 || month==3 || month==5 || …

month==7 || month==8 || month==10 || month==12 nb_days = 31;…

Same applies for the && symbols…

Page 50: “Operators” (i.e. “symbols”)

SHORTCUTS never work

%if angle is between 0 and 90 degreesif 0<=angle<90

quadrant = 1;elseif 90<angle<=180 %quadrant 2

quadrant = 2;end

50

DOES NOT WORK

AS EXPECTED

Instead, rewrite each condition separately!

if 0<=angle && angle<90quadrant = 1;

elseif 90<angle && angle<=180quadrant = 2;

end

Page 51: “Operators” (i.e. “symbols”)

And / Or Mixups

51

It's not technically an “if” problem, but

if month==1 || month==3 || month==5 || …month==7 || month==8 || month==10 || month==12

nb_days = 31;

is MUCH different than

if month==1 && month==3 && month==5 && …month==7 && month==8 && month==10 && month==12

nb_days = 31;

Which month number is equal to both 1 and 3 and 5 and …?

Page 52: “Operators” (i.e. “symbols”)

52

Horrible habits

• The following won't make the code “crash” or “work wrong”.

They're just really bad habits!

Page 53: “Operators” (i.e. “symbols”)

Find the 3 issues

• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');

%choose letter gradeif grade >=90;

letter = 'A';elseif grade >=80 && grade<=90

letter = 'B';elseif grade >=70 && grade<=80

letter = 'C';elseif grade >=60 && grade<=70

letter = 'D';else grade<=60

letter = 'FAIL';end

53

Page 54: “Operators” (i.e. “symbols”)

Issue 1: that semicolon

• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');

%choose letter gradeif grade >=90;

letter = 'A';elseif grade >=80 && grade<=90

letter = 'B';elseif grade >=70 && grade<=80

letter = 'C';elseif grade >=60 && grade<=70

letter = 'D';else grade<=60

letter = 'FAIL';end

54

No semicolon. There is no output to suppress on this line, AND it's not the end of the if statement.

Page 55: “Operators” (i.e. “symbols”)

Issue 2: overdoing it

• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');

%choose letter gradeif grade >=90;

letter = 'A';elseif grade >=80 && grade<=90

letter = 'B';elseif grade >=70 && grade<=80

letter = 'C';elseif grade >=60 && grade<=70

letter = 'D';else grade<=60

letter = 'FAIL';end

55

REDUNDANT conditions

You're asking MATLAB to RE-CHECK a condition MATLAB already knows to be TRUE….

Page 56: “Operators” (i.e. “symbols”)

Issue 3: ERROR!Leave the else alone!

• Common programmer issues%ask user for his/her gradegrade = input('Enter your grade (0-100): ');

%choose letter gradeif grade >=90;

letter = 'A';elseif grade >=80 && grade<=90

letter = 'B';elseif grade >=70 && grade<=80

letter = 'C';elseif grade >=60 && grade<=70

letter = 'D';else grade<=60

letter = 'FAIL';end

56

No condition on the ELSE clause – only on IF and ELSEIF.The last else is for “EVERYTHING” else.

Page 57: “Operators” (i.e. “symbols”)

Write a section of code that will assign the number of days in a given month to a variable

Thirty days hath September,April, June, and November.All the rest have thirty-one,Excepting February alone,And that has twenty-eight days clear,And twenty-nine in each leap year

if-elseif-else Review

57

Page 58: “Operators” (i.e. “symbols”)

Write a section of code that will assign the number of days in a given month to a variable

MATLAB code:

if-elseif-else Review

%Request user to enter the month number (Jan=1, Aug=8)month = input('Enter the month number: ');

% If month is Jan, Mar, May, Jul, Aug, Oct, Decif month==1 || month==3 || month==5 || month==7 || …

month==8 || month==10 || month==12nb_days = 31;

elseif month == 2 % Februarynb_days = 29; % for leap years…

else % every other monthnb_days = 30;

end 58

Page 59: “Operators” (i.e. “symbols”)

%if months are jan,mar,may,jul,aug,oct,decif month==1 || month==3 || month==5 || month==7 || …

month==8 || month==10 || month==12nb_days = 31;

elseif month == 2 %Februarynb_days = 29; % for leap years…

else %every other monthsnb_days = 30;

end

What are some characteristics of this code segment?

What are its limitations?

if-elseif-else Review

59

Page 60: “Operators” (i.e. “symbols”)

60

switch statement

• Allows for evaluation of multiple cases of the same variable

• The switch statement is looking for the variable to have an exact match to one of the cases. (No a<x && x<=b)

• Specification may have multiple values enclosed in braces {…}

• The default case catches any values of the parameter other than the specified cases.

• The default case should trap bad parameter values.

Page 61: “Operators” (i.e. “symbols”)

General Template

switch variablecase specification 1

<code block 1>....case specification n

<code block n>otherwise

<default block>end

61

if <condition 1>

<code block 1>

elseif <condition 2> <code block 2>..elseif <condition n> <code block n>else <default block>end

There is no limit to the number of cases.

Page 62: “Operators” (i.e. “symbols”)

switch Example 1: Multiple Cases

Instead we use…switch month

case {1,3,5,7,8,10,12} % 31-day monthsdays = 31;case 2days = 29; % leap year to be coded..case {4,6,9,11} % 30-day monthsdays = 30; otherwisefprintf('Invalid Entry.\n');

end

62

Let us modify the calendar example from an if to a switch

if month==1 || month== 3 || month== 5 || …month== 7 || month== 8 || month== 10 || month== 12

Big advantage: reduces long OR statements of equality

Page 63: “Operators” (i.e. “symbols”)

63

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

Page 64: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

64

Page 65: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

65

Page 66: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} %30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

66

Page 67: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

67

Page 68: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

68

Page 69: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

6969

Page 70: “Operators” (i.e. “symbols”)

Simulated “Run”

% Suppose month is 4

switch monthcase {1,3,5,7,8,10,12} % 31-days months

days = 31;case 2

days = 29; % leap year to be coded..case {4,6,9,11} % 30-days months

days = 30; otherwise

fprintf('Invalid Entry.\n');end

………

7070

Page 71: “Operators” (i.e. “symbols”)

switch Example 2: strings

71

switch statements can also be used to evaluate stringsmonth = input('Enter the month: ', 's')

switch monthcase {'Jan','March','May','July'... } %31-days -days = 31;case 'Feb'

days = 29; %leap year to be coded..case {'April', 'June','Sept','Nov'} %30-days

days = 30; otherwise

fprintf('Invalid Entry.\n');end

Page 72: “Operators” (i.e. “symbols”)

switch - Menu's

• Several programs request the user to select an item from a menu:

72

Page 73: “Operators” (i.e. “symbols”)

switch Example 3: Menu Options

%ask user what he'd like to domenu_choice = input('Select Item 1 to 4: ');

%direct code to proper actionswitch menu_choice

case 1fprintf('You have selected 1.\n')

case 2fprintf('You have selected a number 2.\n')

case 3fprintf('You have selected a number 3.\n')

case 4fprintf('You have selected a number 4.\n')

otherwisefprintf('Invalid Entry.\n');

end

73

Page 74: “Operators” (i.e. “symbols”)

if versus switch

• As general ideas:

74

if switch

Combination of || statements that check equalityExample:

x==1 || x==2 || x==3 || x==4 Yes √ preferred

Inequalities (<, <=, >=, >) Yes Impossible

Conditions with &&: x == 2 && x == 7 Yes Impossible

Conditions that check multiple variablesSuch as: x==4 && y==7 √ preferred Impossible

Menus ok… √ preferred