CPS 125: Digital Computation CPS 125: Digital Computation and Programmingand Programming
Selection Structures: Selection Structures: ifif and and switchswitch StatementsStatements
Outline Outline
Control StructuresControl Structures ConditionsConditions The The ifif Statement Statement Decision Steps in Algorithms: Case StudyDecision Steps in Algorithms: Case Study The The switchswitch Statement Statement Common Programming ErrorsCommon Programming Errors
Control StructuresControl Structures All programs can be written with three basic All programs can be written with three basic
structuresstructures SequenceSequence SelectionSelection Repetition (Looping, Iteration)Repetition (Looping, Iteration)
Compound statementCompound statement{{
Statement 1;Statement 1;…………Statement n;Statement n;
}}
Selection Selection
Process 1 Process 2
Condition
ConditionCondition
An expression to perform comparisons, which An expression to perform comparisons, which is either false (represented by 0) or true is either false (represented by 0) or true (usually represented by 1, actually could be (usually represented by 1, actually could be anything other than 0)anything other than 0)
Relational expressionsRelational expressions Logical expressionsLogical expressions
Relational ExpressionsRelational Expressions
operand operand relational operatorrelational operator operand operand
OperatorOperator MeaningMeaning ExampleExample
<< less thanless than age < 30age < 30
>> greater thangreater than age > 30age > 30
<=<= less than or equal toless than or equal to taxable <= 20taxable <= 20
>=>= greater than or greater than or equal to equal to
temp >= 98.6temp >= 98.6
==== equal toequal to gradegrade == == 90 90
!=!= not equal tonot equal to number != 250number != 250
Character ExamplesCharacter Examples
‘‘1’ < ‘7’1’ < ‘7’ 11 TrueTrue
‘‘D’ <= ‘Z’D’ <= ‘Z’ 11 TrueTrue
‘‘c’ >= ‘v’c’ >= ‘v’ 00 FalseFalse
‘‘m’ <= ‘M’m’ <= ‘M’ System dependentSystem dependent
‘‘b’ == ‘B’b’ == ‘B’ 00 FalseFalse
More ExamplesMore Examples
key = ‘m’; i = 5; j = 7; k = 12; x = 22.5;
(i + 2) = = (k – 1)(i + 2) = = (k – 1)
((3 * i) – j) < 22((3 * i) – j) < 22
(i + (2 * j)) > k(i + (2 * j)) > k
(‘a’ + 1) = = ‘b’(‘a’ + 1) = = ‘b’
(k + 3) <= ((-j) + (3 * i))(k + 3) <= ((-j) + (3 * i))
(key – 1) > ‘p’(key – 1) > ‘p’
(key + 1) == ‘n’(key + 1) == ‘n’
25 <= (x + 1.0)25 <= (x + 1.0)
Logical ExpressionsLogical Expressions
operand logical operator operand
OperatorOperator NameName UseUse TruthTruth
&&&& Logical Logical andand (a > 10) &&(a > 10) &&
(b < 20)(b < 20)
both operands both operands truetrue
|||| Logical Logical oror (a > 10) || (a > 10) ||
(b < 20)(b < 20)
either operand either operand truetrue
!! Logical Logical complementcomplement
!(a == b)!(a == b) complement complement operandoperand
OperatorOperator PrecedencePrecedencefunction callsfunction calls
! + - & (unary operators)! + - & (unary operators)
* / %* / %
+ -+ -
< <= >= >< <= >= >
== !=== !=
&&&&
||||
==
Operator PrecedenceOperator Precedence
highest
lowest
ExamplesExamples
x = 3.0; y = 4.0; z = 2.0; flag = 0;x = 3.0; y = 4.0; z = 2.0; flag = 0;
1. !flag1. !flag
2. x + y / z <= 3.52. x + y / z <= 3.5
3. !flag || (y + z >= x – z)3. !flag || (y + z >= x – z)
4. !(flag || (y + z >= x – z))4. !(flag || (y + z >= x – z))
Short-circuit evaluationShort-circuit evaluation
English Condition in CEnglish Condition in C
English ConditionEnglish Condition Logical ExpressionLogical Expression
x and y are greater than zx and y are greater than z
x is equal to 1.0 or 3.0x is equal to 1.0 or 3.0
x is in the range z to y, x is in the range z to y, inclusiveinclusive
x is outside the range z to yx is outside the range z to y
Complementing a Condition Complementing a Condition
Complementing item == SENT:Complementing item == SENT:! (item == SENT) ! (item == SENT) or or item != SENTitem != SENT
DeMorgan’s TheoremDeMorgan’s Theorem The complement of The complement of exprexpr11 && expr && expr22 is written as is written as coco
mpmp11 || comp || comp22, where , where compcomp11 is the complement of is the complement of expexprr11 and and compcomp22 is complement of is complement of exprexpr22
The complement of The complement of exprexpr11 || expr || expr22 is written as is written as compcomp11 && comp&& comp22, where , where compcomp11 is the complement of is the complement of exprexpr11 and and compcomp22 is complement of is complement of exprexpr22
age <= 25 && (status == ‘S’ || status == ‘D’)age <= 25 && (status == ‘S’ || status == ‘D’)
Logical AssignmentLogical Assignment
int senior_citizen;int senior_citizen;senior_citizen = (age >= 65);senior_citizen = (age >= 65);Expression !senior_citizen && gender == ‘M’Expression !senior_citizen && gender == ‘M’
int in_range, is_letter;int in_range, is_letter;in_range = (n > -10 && n < 10);in_range = (n > -10 && n < 10);is_letter = (ch >= ‘A’ && ch <= ‘Z’) ||is_letter = (ch >= ‘A’ && ch <= ‘Z’) ||
(ch >= ‘a’ && ch <= ‘z’);(ch >= ‘a’ && ch <= ‘z’);
int even;int even;even = (n % 2 == 0);even = (n % 2 == 0);
The The ifif Statement Statement
SyntaxSyntaxif (condition)if (condition)
statement1;statement1;
elseelse
statement2;statement2; If condition is true, statement1 will be executedIf condition is true, statement1 will be executed If condition is false, statement2 will be executedIf condition is false, statement2 will be executed The The elseelse part is optional part is optional
ExamplesExamples
if (crsr_or_frgt == ‘C’)if (crsr_or_frgt == ‘C’)printf(“Cruiser\n”);printf(“Cruiser\n”);
elseelseprintf(“Frigate\n”);printf(“Frigate\n”);
if crsr_or_frgt == ‘C’if crsr_or_frgt == ‘C’printf(“Cruiser\n”);printf(“Cruiser\n”);
if (crsr_or_frgt == ‘C’);if (crsr_or_frgt == ‘C’);printf(“Cruiser\n”);printf(“Cruiser\n”);
Display “Cruiser”
Display “Frigate”
== ‘C’ ?
TF
Compound StatementsCompound Statements
SyntaxSyntaxif (if (conditioncondition) )
{ { statements;statements;
}}
elseelse
{ { statements;statements;
}}
if (ctri <= MAX_SAFE_CTRI) {
printf(“Car #%d: safe\n”, auto_id);
safe = safe + 1;
}
else { printf(“Car #%d: unsafe\n”, auto_id); unsafe = unsafe + 1;}
if (ctri <= MAX_SAFE_CTRI)
printf(“Car #%d: safe\n”, auto_id);
safe = safe + 1;
else ……
Example Example
if (x > y) {
temp = x; /* Store old x in temp */
x = y; /* Store old y in x */
y = temp; /* Store old x in y */
}
Tracing its execution with x = 12.5; y = 5.0;
Tracing an Tracing an ifif Statement Statement
StatementsStatements xx yy temptemp
12.512.5 5.05.0 ??
if (x > y) {if (x > y) {
temp = x;temp = x;
x = y;x = y;
y = temp;y = temp;
Nested Nested ifif Statements Statements
if (expression1)if (expression1)
statement1;statement1;
elseelse
if (expression2)if (expression2)
statement2;statement2;
elseelse
statement3;statement3;
if (x > 0)if (x > 0)num_pos = num_pos + 1;num_pos = num_pos + 1;
elseelseif (x < 0)if (x < 0)
num_neg = num_neg + 1;num_neg = num_neg + 1;elseelse
num_zero = num_zero + 1;num_zero = num_zero + 1;
if (x > 0)if (x > 0)num_pos = num_pos + 1;num_pos = num_pos + 1;
if (x < 0)if (x < 0)num_neg = num_neg + 1;num_neg = num_neg + 1;
if (x == 0)if (x == 0)num_zero = num_zero + 1;num_zero = num_zero + 1;
Multiple Variables to TestMultiple Variables to Test
/* print a message if all criteria are met *//* print a message if all criteria are met */if (marital_status == ‘S’)if (marital_status == ‘S’) if (gender == ‘M’ )if (gender == ‘M’ ) if (age >= 18)if (age >= 18) if (age <= 26)if (age <= 26) printf(“ All criteria are met. \n”);printf(“ All criteria are met. \n”);
if (marital_status == ‘S’ && gender == ‘M’ && if (marital_status == ‘S’ && gender == ‘M’ && age >= 18 && age <= 26 )age >= 18 && age <= 26 )
printf(“ All criteria are met. \n”);printf(“ All criteria are met. \n”);
if (road_status == ‘S’)if (road_status == ‘S’)if (temp > 0) {if (temp > 0) {
printf(“Wet roads ahead\n”);printf(“Wet roads ahead\n”);printf(“Stopping time doubled\n”);printf(“Stopping time doubled\n”);
} } else {else {
printf(“Icy roads ahead\n”);printf(“Icy roads ahead\n”);printf(“Stopping time quadrupled\n”);printf(“Stopping time quadrupled\n”);
}}elseelse
printf(“Drive carefully\n”);printf(“Drive carefully\n”);
Nested Nested ifif Statements Statements
May be nested to any depthMay be nested to any depth Each “statement” may be a compound
statement else matches closest unmatched if Braces may be used to change if-else matching
Example Example
What is the difference, if any?
if (expression1) if (expression2)
statement1;else
statement2;
if (expression1) if (expression2)
statement1; else
statement2;
if (road_status == ‘D’)if (road_status == ‘D’)printf(“Drive carefully\n”);printf(“Drive carefully\n”);
elseelseif (temp > 0) {if (temp > 0) {
printf(“Wet roads ahead\n”);printf(“Wet roads ahead\n”);printf(“Stopping time doubled\n”);printf(“Stopping time doubled\n”);
} } else {else {
printf(“Icy roads ahead\n”);printf(“Icy roads ahead\n”);printf(“Stopping time quadrupled\n”);printf(“Stopping time quadrupled\n”);
}}
Multiple-Alternative DecisionMultiple-Alternative Decision
if (expression_1)if (expression_1)statement_1;statement_1;
else if (expression_2)else if (expression_2)statement_2;statement_2;
…………else if (expression_n)else if (expression_n)
statement_n;statement_n;elseelse
statement_e;statement_e;
ExampleExample
if (marks >= 75)if (marks >= 75) printf (“Distinction\n”) ;printf (“Distinction\n”) ;else if (marks >= 60)else if (marks >= 60) printf (“Pass\n”) ;printf (“Pass\n”) ;else if (marks >= 50)else if (marks >= 50) printf (“Average\n”) ;printf (“Average\n”) ;elseelse printf (“Fail\n”) ;printf (“Fail\n”) ;
if (marks >= 50)if (marks >= 50) printf (“Average\n”) ;printf (“Average\n”) ;else if (marks >= 60)else if (marks >= 60) printf (“Pass\n”) ;printf (“Pass\n”) ; else if (marks >= 75)else if (marks >= 75) printf (“Distinction\n”) ;printf (“Distinction\n”) ;elseelse printf (“Fail\n”) ;printf (“Fail\n”) ;
Order of the conditions will affect the outcome as well as efficiency.
Decision TableDecision Table
Salary Range ($)Salary Range ($) Base Tax ($)Base Tax ($) Percentage of Percentage of ExcessExcess
0.00- 14,999.990.00- 14,999.99 0.000.00 1515
15,000.00- 29,999.9915,000.00- 29,999.99 2,250.002,250.00 1818
30,000.00- 49,999.9930,000.00- 49,999.99 5,400.005,400.00 2222
50,000.00- 79,999.9950,000.00- 79,999.99 11,000.0011,000.00 2727
80,000.00- 150,000.0080,000.00- 150,000.00 21,600.0021,600.00 3333
Case Study: Computing Compass Case Study: Computing Compass BearingsBearings
Problem: Write a program that automates the Problem: Write a program that automates the table you use to transform compass headings table you use to transform compass headings in degrees (0 to 360 degrees) to compass in degrees (0 to 360 degrees) to compass bearings. The program should require entry of bearings. The program should require entry of a compass heading, such as 110 degrees, and a compass heading, such as 110 degrees, and should display the corresponding bearing (e.g. should display the corresponding bearing (e.g. south 70 degrees east).south 70 degrees east).
AnalysisAnalysis Input: double heading; /* in degree */Input: double heading; /* in degree */ Output: equivalent bearing message (direction you Output: equivalent bearing message (direction you
face, an angle between 0-90, direction to turn)face, an angle between 0-90, direction to turn)
Heading in DegreesHeading in Degrees Bearing ComputationBearing Computation
0 – 89.999……0 – 89.999…… north (heading) eastnorth (heading) east
90 – 179.999……90 – 179.999…… south (180.0 – heading) eastsouth (180.0 – heading) east
180 – 269.999……180 – 269.999…… south (heading – 180.0) westsouth (heading – 180.0) west
270 – 360270 – 360 north (360.0 – heading) westnorth (360.0 – heading) west
Case StudyCase Study
DesignDesign Initial Algorithm:Initial Algorithm: 1. Display instructions1. Display instructions 2. Get the compass heading2. Get the compass heading 3. Display the equivalent compass bearing3. Display the equivalent compass bearing Algorithm Refinement on Step 3Algorithm Refinement on Step 3 multiple alternative multiple alternative ifif statements statements
catch the value out of range (0, 360), show the catch the value out of range (0, 360), show the error messageerror message
The The switchswitch Statement Statementswitch ( integer or char expression ){
case const1:statements 1break;
case const2:statements 2;break;
……default:
statements d;break;
}
switchswitch
Selection is based on one variable or Selection is based on one variable or expressionexpression
MUST have MUST have INTEGER or CHARINTEGER or CHAR condition condition for branchingfor branching
Like a special instance of if else-if else ...Like a special instance of if else-if else ... Evaluates expression then compares it to Evaluates expression then compares it to
CONSTANT VALUES in each caseCONSTANT VALUES in each case
switchswitch
There can be as many “case” values as neededThere can be as many “case” values as needed There can be as many “statements” as needed
following the ‘:’ (no brace needed) There can be as few “statements” as needed There can be as few “statements” as needed
following the ‘:’following the ‘:’ The default statement is optional
Flowchart of Flowchart of switchswitch Statement Statement
?
1 2 3 default
switch (class) { case 'B': case 'b': printf("Battleship\n");
break; case 'C': case 'c': printf("Cruiser\n");
break; case 'F': case 'f': printf("Frigate\n");
break; default: printf("Unknown ship class %c\n", class); }
/* determine average life expectancy of a standard light bulb */ switch (watts) { case 25: life = 2500;
break; case 40: case 60: life = 1000;
break; case 75: case 100: life = 750;
break; default: life =0; }
Common Programming ErrorsCommon Programming Errors
Cannot use a < x < b to represent a range comparison, Cannot use a < x < b to represent a range comparison, instead, we should use x > a && x < binstead, we should use x > a && x < be.g. if (0 <= x <= 4)e.g. if (0 <= x <= 4)
printf(“Condition is true\n”);printf(“Condition is true\n”);
When x = 5, what is the result?When x = 5, what is the result? Equality operator is == instead of =Equality operator is == instead of =
e.g. int age = 30;e.g. int age = 30;
if (age = 40)if (age = 40)
printf(“Happy Birthday”);printf(“Happy Birthday”);
Always prints Happy Birthday!!!!
Common Programming ErrorsCommon Programming Errors
if if ((conditioncondition) {) {
…………
}} Use braces to change the if-else orderUse braces to change the if-else order Always try to use multiple alternative format Always try to use multiple alternative format
when writing a nested when writing a nested ifif statement statement elseelse match with closest unmatched match with closest unmatched ifif switchswitch statement format statement format
Top Related