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

Lecture 03 - Selection

The document discusses selection structures in C programming, specifically the if statement. It covers the basic syntax of if statements, including if/else statements and using if statements with logical and relational operators to test conditions. Examples are provided to illustrate simple if statements as well as using if statements with compound statements or multiple statements inside the curly braces. The last few pages discuss tracing if statements by hand to step through examples and verify the logic and output.

Uploaded by

Süleyman Golbol
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)
12 views

Lecture 03 - Selection

The document discusses selection structures in C programming, specifically the if statement. It covers the basic syntax of if statements, including if/else statements and using if statements with logical and relational operators to test conditions. Examples are provided to illustrate simple if statements as well as using if statements with compound statements or multiple statements inside the curly braces. The last few pages discuss tracing if statements by hand to step through examples and verify the logic and output.

Uploaded by

Süleyman Golbol
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/ 28

3/4/2020

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


- Unknown

CSE102
Computer Programming with C

2018-2020 Spring Semester


Selection Structures: “if” and “switch”
© 2015-2020 Yakup Genç

Largely adapted from J.R. Hanly, E.B. Koffman, F.E. Sevilgen, and others…

Control Structures
• Controls the flow of program execution
– Sequence
– Selection
– Repetition
• 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
– if
– switch
• They select one statement block and executes them

March 2020 CSE102 Lecture 03 2

1
3/4/2020

Conditions
• 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 2020 CSE102 Lecture 03 3

Relational and Equality Operators

March 2020 CSE102 Lecture 03 4

2
3/4/2020

Logical Operators
• 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 2020 CSE102 Lecture 03 5

Operator Precedence

March 2020 CSE102 Lecture 03 6

3
3/4/2020

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

March 2020 CSE102 Lecture 03 7

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 2020 CSE102 Lecture 03 8

4
3/4/2020

Logical Expressions
• min <= x && x <= max

• z > x || x > y

• You can compare characters


‘a’ <= ch && ch <= ‘z’

• You can use DeMorgan’s Theorem for simplification


!(‘a’ <= ch && ch <= ‘z’)
‘a’ > ch || ch > ‘z’

March 2020 CSE102 Lecture 03 9

Logical Assignment
• Integers are used to represent logical values
– non-zero value is true
– zero is false

senior_citizen = (age >= 65);


not_senior_citizen = !senior_citizen;
male_senior_citizen = senior_citizen && gender == ‘M’;

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


(‘A’ <= ch && ch <= ‘Z’);

even = (n % 2 == 0)

March 2020 CSE102 Lecture 03 10

10

5
3/4/2020

The if statement
• 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;

March 2020 CSE102 Lecture 03 11

11

Flowcharts of if Statements

(a) Two Alternatives and (b) One Alternative


March 2020 CSE102 Lecture 03 12

12

6
3/4/2020

The if statement

if (condition) if (x > 0)
statement; printf(“positive”);

if (condition) if (x > 0)
statement; printf(“positive”);
else else
statement; printf(“negative”);

March 2020 CSE102 Lecture 03 13

13

• What is the output?

if age > 65
printf(“senior”);
printf(“citizen.\n”);

March 2020 CSE102 Lecture 03 14

14

7
3/4/2020

• What is the output?

if (age > 65);


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

March 2020 CSE102 Lecture 03 15

15

• What is the output?

if (age > 65) {


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

March 2020 CSE102 Lecture 03 16

16

8
3/4/2020

if statement with compound statements

if (condition) { if (radius > 0){


statements circ = 2*PI*radius;
} printf(“%f”, circ);
}

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

March 2020 CSE102 Lecture 03 17

17

if Statement to Order x and y

March 2020 CSE102 Lecture 03 18

18

9
3/4/2020

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
– Try inputs that cause the condition to be false and true…
• Execute each statement exactly as the computer
– Don’t assume the way of execution
– Takes time
• But saves time as well

March 2020 CSE102 Lecture 03 19

19

Hand Tracing an IF Statement

Line No x y temp
5 3
1
2 5
3 3
4 5
5

March 2020 CSE102 Lecture 03 20

20

10
3/4/2020

Hand Tracing an IF Statement

Line No x y temp
1 3
1
2
3
4
5

March 2020 CSE102 Lecture 03 21

21

Hand Tracing an IF Statement

Line No x y temp
3 1
1
2 3
3 1
4 3
5

March 2020 CSE102 Lecture 03 22

22

11
3/4/2020

Case Study: Simple Math Tool


Simple Math Tool to teach subtraction to a first grade student

Algorithm
1. Generate two single-digit integers randomly
number1 and number2 with number1 > number2
2. Display the question
such as “What is 9 – 2?”
3. Read student’s answer
4. Display a message indicating whether the answer is
correct

March 2020 CSE102 Lecture 03 23

23

Case Study: Water Bill Problem

• Compute customers water bill


– Demand charge = $35
– Consumption charger = $1.10 per thousand gallons
– Late charge for unpaid balance = $2
• Inputs:
– Meter readings: previous, current
– Unpaid balance
• Outputs:
– Water bill : use charge, late chage

March 2020 CSE102 Lecture 03 24

24

12
3/4/2020

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 2020 CSE102 Lecture 03 25

25

Structure Chart for Water Bill Problem

March 2020 CSE102 Lecture 03 26

26

13
3/4/2020

Water Bill Problem

(continued)

March 2020 CSE102 Lecture 03 27

27

Water Bill Problem

March 2020 CSE102 Lecture 03 28

28

14
3/4/2020

Water Bill Problem

(continued)

March 2020 CSE102 Lecture 03 29

29

Water Bill Problem

March 2020 CSE102 Lecture 03 30

30

15
3/4/2020

Water Bill Problem

March 2020 CSE102 Lecture 03 31

31

Water Bill Problem

March 2020 CSE102 Lecture 03 32

32

16
3/4/2020

Water Bill Problem

March 2020 CSE102 Lecture 03 33

33

Sample Run of Water Bill Program

March 2020 CSE102 Lecture 03 34

34

17
3/4/2020

Program Style
• Consistent use of names in functions
– Use same names to reference the same information
– Ex: late_charge in three functions
• They are all different variables but same information
• Cohesive functions
– Each function should perform single operation
– 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 2020 CSE102 Lecture 03 35

35

Case Study: Water bill with conservation requirement

• Modify the program


– Conservation requirement: 5% decrease each year
– Charge twice if more than %95 of the last year

• What changes are required?

March 2020 CSE102 Lecture 03 36

36

18
3/4/2020

Structure Chart for Water Bill Problem

March 2020 CSE102 Lecture 03 37

37

Function comp_use_charge Revised

March 2020 CSE102 Lecture 03 38

38

19
3/4/2020

Nested if statements
• if statement in another if statement
• Used if there are more than one alternative decisions

if (x > 0)
num_pos = num_pos + 1;
else
if (x < 0)
num_neg = num_neg + 1;
else
num_zero = num_zero + 1;

March 2020 CSE102 Lecture 03 39

39

Alternative ways
if (x > 0) if (x > 0)
num_pos = num_pos + 1; num_pos = num_pos + 1;
else if (x < 0)
if (x < 0) num_neg = num_neg + 1;
num_neg = num_neg + 1; if (x == 0)
else num_zero = num_zero + 1;
num_zero = num_zero + 1;

Less efficient
Less readable

March 2020 CSE102 Lecture 03 40

40

20
3/4/2020

Alternative ways
if (x > 0) if (x > 0)
num_pos = num_pos + 1; num_pos = num_pos + 1;
else else if (x < 0)
if (x < 0) num_neg = num_neg + 1;
num_neg = num_neg + 1; else
else num_zero = num_zero + 1;
num_zero = num_zero + 1;

Better way writing

March 2020 CSE102 Lecture 03 41

41

Example: Payroll system


• Compute tax amount for a salary
• Decision table:

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 2020 CSE102 Lecture 03 42

42

21
3/4/2020

Function comp_tax

March 2020 CSE102 Lecture 03 43

43

Flowchart of Road Sign Decision

March 2020 CSE102 Lecture 03 44

44

22
3/4/2020

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


if (temp > 0) { if (temp > 0) {
printf(“wet road”); printf(“wet road”);
} else { }
printf(“icy road”); else
} printf(“drive carefully”);
else
printf(“drive carefully”);

March 2020 CSE102 Lecture 03 45

45

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


if (temp > 0) { if (temp > 0) {
printf(“wet road”); printf(“wet road”);
} else { }
printf(“icy road”); } else
} printf(“drive carefully”);
else
printf(“drive carefully”);

C associates an else with the most recent if statement


Use braces to force association

March 2020 CSE102 Lecture 03 46

46

23
3/4/2020

The switch statement


• Select one of the several alternatives
– Selection is based on the value of a single variable (of type
int of char not double)

March 2020 CSE102 Lecture 03 47

47

switch with break


switch(Grade) {
case 'A' : printf("Excellent\n");
break;

case 'B' : printf("Good\n");


break;

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");


}

For instance when Grade is ‘B’, the output is:


Good
March 2020 CSE102 Lecture 03 48

48

24
3/4/2020

The switch statement


switch (controlling expression) {
label case_1:
statements;
break;
label case_2:
statements;
break;
....
label case_n:
statements;
break;
default:
statements;
}

March 2020 CSE102 Lecture 03 49

49

switch without break


switch(Grade) {
case 'A' : printf("Excellent\n");
case 'B' : printf("Good\n" );
case 'C' : printf("OK\n" );
case 'D' : printf("Mmmmm....\n");
case 'F' : printf("You must do better than this\n");
default : printf("What is your grade anyway?\n");
}

For instance when Grade is ‘A’, the output is:


Excellent
Good
OK
Mmmmm....
You must do better than this
What is your grade anyway?

March 2020 CSE102 Lecture 03 50

50

25
3/4/2020

Example of a switch Statement

March 2020 CSE102 Lecture 03 51

51

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 2020 CSE102 Lecture 03 52

52

26
3/4/2020

Another switch example


switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: numDays = 31;
break;
case 4:
case 6:
case 9:
case 11: numDays = 30;
break;
case 2: if((year % 4) == 0)
numDays = 29;
else
numDays = 28;
break;
default: printf("You have entered a wrong month number.\n");
}
March 2020 CSE102 Lecture 03 53

53

Another switch example


/* Print the day of the week given a number between 1
* and 7 where 1 is Monday */
void
print_day_of_week(int day)
{
switch (day) {
case 1: printf(“Monday”); break;
case 2: printf(“Tuesday”); break;
case 3: printf(“Wednesday”); break;
case 4: printf(“Thursday”); break;
case 5: printf(“Friday”); break;
case 6: printf(“Saturday”); break;
default: printf(“Sunday”);
}

March 2020 CSE102 Lecture 03 54

54

27
3/4/2020

Payroll System using Switch?

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 2020 CSE102 Lecture 03 55

55

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

March 2020 CSE102 Lecture 03 56

56

28

You might also like