0% found this document useful (0 votes)
5 views

Lecture 02 - Selection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 02 - Selection

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

3/9/2022

“Stupidity is while (1) { tryAgain(); }”


- Unknown
Control Structures
• Controls the flow of program execution

CSE102
• Sequence
• Selection
• Repetition

Computer Programming with C • We used sequence flow


• Control flows from one statement to next one
• A compound statement in braces
• Ex: function body
• We will learn selection control statements
2021-2022 Spring Semester • if
Selection Structures: “if” and “switch” • switch
© 2015-2022 Yakup Genç • They select one statement block and executes them

March 2022 CSE102 Computer Programming 2

Conditions Relational and Equality Operators


• We need conditions in selection structures

• Ex: Testing the value of a variable


rest_heart_rate > 75
• true (1): if greater than 75
• false (0): otherwise

variable relational-operator constant


variable equality-operator constant

expression equality-operator expression

• C accepts any nonzero value as a true

March 2022 CSE102 Computer Programming 3 March 2022 CSE102 Computer Programming 4

1
3/9/2022

Logical Operators Operator Precedence


• Used to form more complicated logical expressions
• And (&&)
• Or (||)
• Not (!)
• Ex:
salary < MIN_SALARY || dependents > 5
temperature > 90.0 && humidity > 0.90
n >= 0 && n <= 100
!(n >= 0 && n <= 100)

March 2022 CSE102 Computer Programming 5 March 2022 CSE102 Computer Programming 6

Evaluation for !flag || (y + z >= x - z) Short-Circuit Evaluation


• For logical && and || operations C evaluates the left operand first and
right operand later
• C stops evaluation
• If the operation is && and left operand is false
• Value of the expression is false
• If the operation is || and left operand is true
• Value of the expression is true

March 2022 CSE102 Computer Programming 7 March 2022 CSE102 Computer Programming 8

2
3/9/2022

Logical Expressions Logical Assignment


• min <= x && x <= max • Integers are used to represent logical values
• non-zero value is true
• z > x || x > y • zero is false

senior_citizen = (age >= 65);


• You can compare characters not_senior_citizen = !senior_citizen;
‘a’ <= ch && ch <= ‘z’ male_senior_citizen = senior_citizen && gender == ‘M’;

is_letter = (‘a’ <= ch && ch <= ‘z’) ||


• You can use DeMorgan’s Theorem for simplification (‘A’ <= ch && ch <= ‘Z’);
!(‘a’ <= ch && ch <= ‘z’)
even = (n % 2 == 0)
‘a’ > ch || ch > ‘z’

March 2022 CSE102 Computer Programming 9 March 2022 CSE102 Computer Programming 10

The if statement Flowcharts of if Statements


• if statement is the primary selection structure
• Two alternatives
• Selects one of two alternative statement blocks
if (rest_heart_rate > 56)
printf(“Keep up the exercise program! \n”);
else
printf(“You heart is in excellent health! \n”);

• One alternative
• Executes the statement block or not
if (x != 0.0)
product = product * x;

(a) Two Alternatives and (b) One Alternative


March 2022 CSE102 Computer Programming 11 March 2022 CSE102 Computer Programming 12

3
3/9/2022

The if statement
• What is the output?
if (condition) if (x > 0)
statement; printf(“positive”); if age > 65
printf(“senior”);
if (condition) if (x > 0) printf(“citizen.\n”);
statement; printf(“positive”);
else else
statement; printf(“negative”);

March 2022 CSE102 Computer Programming 13 March 2022 CSE102 Computer Programming 14

• What is the output? • What is the output?

if (age > 65); if (age > 65) {


printf(“senior”); printf(“senior”);
printf(“citizen.\n”); printf(“citizen.\n”);
}

March 2022 CSE102 Computer Programming 15 March 2022 CSE102 Computer Programming 16

4
3/9/2022

if statement with compound statements if Statement to Order x and y


if (radius > 0){
if (condition) { circ = 2*PI*radius;
statements printf(“%f”, circ);
} }

if (radius > 0) {
if (condition) { circ = 2*PI*radius;
statements printf(“%f”, circ);
} }
else { else {
statements printf(“Radius is negative!..”);
} }

March 2022 CSE102 Computer Programming 17 March 2022 CSE102 Computer Programming 18

Tracing an if statement Hand Tracing an IF Statement

Hand trace = desk check


• To verify the correctness
• Step-by-step simulation of algorithm (or statements) on paper
• Use simple input values
• Trace each case
Line No x y temp
• Try inputs that cause the condition to be false and true…
5 3
• Execute each statement exactly as the computer
• Don’t assume the way of execution 1 5

• Takes time 2 3
• But saves time as well 3 5
4
5

March 2022 CSE102 Computer Programming 19 March 2022 CSE102 Computer Programming 20

5
3/9/2022

Hand Tracing an IF Statement Hand Tracing an IF Statement

Line No x y temp Line No x y temp


1 3 3 1
1 1 3
2 2 1
3 3 3
4 4
5 5

March 2022 CSE102 Computer Programming 21 March 2022 CSE102 Computer Programming 22

Case Study: Simple Math Tool Case Study: Water Bill Problem
Simple Math Tool to teach subtraction to a first grade student • Compute customers water bill
• Demand charge = $35
• Consumption charger = $1.10 per thousand gallons
Algorithm
• Late charge for unpaid balance = $2
1. Generate two single-digit integers randomly
number1 and number2 with number1 > number2 • Inputs:
2. Display the question • Meter readings: previous, current
such as “What is 9 – 2?” • Unpaid balance
3. Read student’s answer
• Outputs:
4. Display a message indicating whether the answer is correct
• Water bill : use charge, late chage

March 2022 CSE102 Computer Programming 23 March 2022 CSE102 Computer Programming 24

6
3/9/2022

Water Bill Problem Structure Chart for Water Bill Problem

• Algorithm:
1. Display user instructions
2. Get data
3. Compute use charge
4. Determine late charge
5. Figure bill amount
6. Display the bill and charges

• Functions
 Data requirements
 Design and algorithm

March 2022 CSE102 Computer Programming 25 March 2022 CSE102 Computer Programming 26

Water Bill Problem Water Bill Problem

(continued)

March 2022 CSE102 Computer Programming 27 March 2022 CSE102 Computer Programming 28

7
3/9/2022

Water Bill Problem Water Bill Problem

(continued)
March 2022 CSE102 Computer Programming 29 March 2022 CSE102 Computer Programming 30

Water Bill Problem Water Bill Problem

March 2022 CSE102 Computer Programming 31 March 2022 CSE102 Computer Programming 32

8
3/9/2022

Water Bill Problem Sample Run of Water Bill Program

March 2022 CSE102 Computer Programming 33 March 2022 CSE102 Computer Programming 34

Program Style Case Study: Water bill with conservation requirement

• Consistent use of names in functions • Modify the program


• Use same names to reference the same information • Conservation requirement: 5% decrease each year
• Ex: late_charge in three functions
• They are all different variables but same information
• Charge twice if more than %95 of the last year
• Cohesive functions
• Each function should perform single operation • What changes are required?
• Easier to read, write, debug and maintain
• More reusable
• Use constant macros
• Can be used anywhere in the same file
• Statements are easier to understand (more descriptive)
• Easier to maintain

March 2022 CSE102 Computer Programming 35 March 2022 CSE102 Computer Programming 36

9
3/9/2022

Structure Chart for Water Bill Problem Function comp_use_charge Revised

March 2022 CSE102 Computer Programming 37 March 2022 CSE102 Computer Programming 38

Nested if statements Alternative ways


• if statement in another if statement if (x > 0) if (x > 0)
• Used if there are more than one alternative decisions num_pos = num_pos + 1; num_pos = num_pos + 1;
else if (x < 0)
if (x < 0) num_neg = num_neg + 1;
if (x > 0)
num_pos = num_pos + 1; num_neg = num_neg + 1; if (x == 0)
else else num_zero = num_zero + 1;
if (x < 0) num_zero = num_zero + 1;
num_neg = num_neg + 1;
else
Less efficient
num_zero = num_zero + 1;
Less readable

March 2022 CSE102 Computer Programming 39 March 2022 CSE102 Computer Programming 40

10
3/9/2022

Alternative ways Example: Payroll system

if (x > 0) if (x > 0)
• Compute tax amount for a salary
num_pos = num_pos + 1; num_pos = num_pos + 1;
else else if (x < 0) • Decision table:
if (x < 0) num_neg = num_neg + 1;
Salary Tax rate
num_neg = num_neg + 1; else
0 – 15,000 15
else num_zero = num_zero + 1;
num_zero = num_zero + 1; 15,000 – 30,000 18
30,000 – 50,000 22
50,000 – 80,000 27
Better way writing
80,000 – 150,000 33

March 2022 CSE102 Computer Programming 41 March 2022 CSE102 Computer Programming 42

Function comp_tax Flowchart of Road Sign Decision

March 2022 CSE102 Computer Programming 43 March 2022 CSE102 Computer Programming 44

11
3/9/2022

if (road_status == ‘S’) if (road_status == ‘S’) if (road_status == ‘S’) if (road_status == ‘S’){


if (temp > 0) { if (temp > 0) { if (temp > 0) { if (temp > 0) {
printf(“wet road”); printf(“wet road”); printf(“wet road”); printf(“wet road”);
} else { } } else { }
printf(“icy road”); else printf(“icy road”); } else
} printf(“drive carefully”); } printf(“drive carefully”);
else else
printf(“drive carefully”); printf(“drive carefully”);
C associates an else with the most recent if statement
Use braces to force association
March 2022 CSE102 Computer Programming 45 March 2022 CSE102 Computer Programming 46

The switch statement switch with break


• Select one of the several alternatives switch(Grade) {
case 'A': printf("Excellent\n");
• Selection is based on the value of a single variable (of type int of char not break;
double) case 'B': printf("Good\n");
For instance when Grade is ‘B’, the output is:

break; Good

case 'C': printf("OK\n");


break;
case 'D': printf("Mmmmm....\n");
break;
case 'F': printf("You must do better than this\n");
break;
default: printf("What is your grade anyway?\n");
}

March 2022 CSE102 Computer Programming 47 March 2022 CSE102 Computer Programming 48

12
3/9/2022

The switch statement switch without break


switch (controlling expression) { switch(Grade) {
label case_1: case 'A' : printf("Excellent\n");
statements; case 'B' : printf("Good\n" );
break;
case 'C' : printf("OK\n" );
label case_2:
case 'D' : printf("Mmmmm....\n");
statements;
case 'F' : printf("You must do better than this\n");
break;
.... default : printf("What is your grade anyway?\n");
label case_n: }
For instance when Grade is ‘A’, the output is:
statements; Excellent
break; Good
default: OK
statements; Mmmmm....
} You must do better than this
What is your grade anyway?
March 2022 CSE102 Computer Programming 49 March 2022 CSE102 Computer Programming 50

Example of a switch Statement The switch statement


• Statements following the matching case label are executed until a
break statement
• After the break the rest of the switch statement is skipped
• If no case label matches statements after the default label are
executed

• The switch statement is more readable


• Try to use default case

March 2022 CSE102 Computer Programming 51 March 2022 CSE102 Computer Programming 52

13
3/9/2022

Another switch example Another switch example


switch (month) { /* Print the day of the week given a number between 1
case 1:
case 3:
* and 7 where 1 is Monday */
case 5: void
case 7: print_day_of_week(int day)
case 8: {
case 10:
case 12: numDays = 31;
switch (day) {
break; case 1: printf(“Monday”); break;
case 4: case 2: printf(“Tuesday”); break;
case 6: case 3: printf(“Wednesday”); break;
case 9:
case 11: numDays = 30;
case 4: printf(“Thursday”); break;
break; case 5: printf(“Friday”); break;
case 2: if((year % 4) == 0) case 6: printf(“Saturday”); break;
numDays = 29; default: printf(“Sunday”);
else
numDays = 28;
}
break;
default: printf("You have entered a wrong month number.\n");
}
March 2022 CSE102 Computer Programming 53 March 2022 CSE102 Computer Programming 54

Payroll System using Switch? Problem I – Week Number to Day


• Given the week number of the day, print the name of the day
• E.g., 1  Monday, 7  Sunday
Salary Tax rate
0 – 15,000 15
15,000 – 30,000 18
30,000 – 50,000 22
50,000 – 80,000 27
80,000 – 150,000 33

March 2022 CSE102 Computer Programming 55 March 2022 CSE102 Computer Programming 56

14
3/9/2022

Thanks for listening!

15

You might also like