By the end of this chapter, students will be able to:
Explain the operation of if, else if and else
Explain the operation of relational and logical operators
Analyze programs that use branching
Write programs that use branching to solve problems
Hybridoma Technology ( Production , Purification , and Application )
Chapter 3 branching v4
1. Chapter 3
Branching
(Selection)
By the end of this chapter, students will be able to:
Explain the operation of if, else if and else
Explain the operation of relational and logical operators
Analyze programs that use branching
Write programs that use branching to solve problems
2. - sun13/04/2020 38PROG - Chapter 3: Branching 2
Introduction
• 3 types of control structures:
• Sequential
• Selection
• Repetition
• So far, we only use Sequential
control structure in our program
• E.g.: Simple Ticketing System
Enter quantity:
Total: $50.00
5
• Such a program isn’t very useful
• It is not able to perform
different course of actions for
different conditions
• E.g.: How do we implement the
program that will give discount
for purchasing more?
Answer:
Use
Selection
control structure,
a.k.a. Branching
3. - sun13/04/2020 38PROG - Chapter 3: Branching 3
• Algorithm: a step by step procedure
to perform a task
• Flowchart and pseudocode
• used to formulate and visualize
algorithm before implementing it
• Flowchart: uses diagram
• Pseudocode: natural language
Algorithm, Flowchart, Pseudocode
Terminal Represent Start or
End
Processing Data operation or
manipulation
Decision Operation that has
2 alternatives, true
of false
Flow line Indicate the flow of
logic
Four basic symbols of flowchart
Start
Set unit
price u = 10
Get input q
Calc. total
t = q x u
Display
total price, t
End
q>5?
Lower unit
price u = 9
yes
no
Prompt user
for quantity
Pseudocode
1. Set unit price, u = 10
2. Prompt user to enter quantity
3. Read input, q
4. If q > 5
change u to 9
5. Calculate total price t = q × u
6. Display total price t
Here is the algorithm for the program to
give 10% discount when buying more than 5
• Which one shows the logic
more clearly and quickly?
• Which one is easier to do?
4. - sun13/04/2020 38PROG - Chapter 3: Branching 4
Example of Branching in C program
• What is the total price when
the quantity is 6? 54
- What is the condition? q>5
- What is the action? u=9.0
• What about when the
quantity is 5? 50
Start
Set unit
price u = 10
Get input q
Calc. total
t = q x u
Display
total price, t
End
q>5?
Lower unit
price u = 9
yes
no
Prompt user
for quantity
Pseudocode
1. Set unit price, u = 10
2. Prompt user to enter quantity
3. Read input, q
4. If q > 5
change u to 9
5. Calculate total price t = q × u
6. Display total price t
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
void main(void)
{
int q;
float t, u;
u = 10.0;
printf("Enter quantity: ");
scanf("%d", &q);
if (q > 5)
{
u = 9.0;
}
t = q*u;
printf("Total: $%.2f", t);
}
5. - sun13/04/2020
38PROG - Chapter 3: Branching
5
How does if statements work?
if (q > 5) {
u = 9.0;
}
06
07
08
1. Evaluate the condition 2. If it is TRUE, execute the
statements within the
braces
3. If it is FALSE, skip to the
next statement
A condition or a relational expression can produce a value
after being evaluated, just like the math expression can
- In math expression, 3 + 5 produces 8
- In relational expression
- 6 > 4 produces TRUE or 1
- 2 > 4 produces FALSE or 0
- In C, FALSE is 0 and TRUE is any value other than 0
6. - sun13/04/2020 38PROG - Chapter 3: Branching 6
Relational Operators
Operators
in Maths
Relational
Operators
Meaning
< < less than
> > greater than
= == equal to
<= less than or equal to
>= greater than or equal to
!= not equal to
• There 6 relational operators in C, as shown below:
7. - sun13/04/2020 38PROG - Chapter 3: Branching 7
3.1a: if statement & usage of {}
• Compile & run the program below and answer the
questions on the next page
8. - sun13/04/2020 38PROG - Chapter 3: Branching 8
3.1a: if statement & usage of {}
Task Input Observation Explanation
1 Run the program 62 Display L10–12
and L14
As num is 62, it satisfies the if’s condition
(num >= 60). The program will then enter
the if block (L10-12) and run the codes. It
proceeds to run L14 after that.
54 Display L14
only
As num is 54, it fails to satisfy the if’s
condition (num >= 60). The program will
skip the if block (L10-12) and proceed to run
L14.
2 Change >= of L8
to =>, re-compile
- Error: identifier
expected
The compiler sees num => 60 as an
assignment statement (num =). However
>60 is not a valid identifier. Hence the error.
3 Remove { and }
at L9 and L13.
Run & compare
result to Task 1
62 Same as before Logic error cannot be observed for this input
54 Display L11,
L12 and L14
Without the curly brackets, only the line next
to if (L10) is in the if block. This means that
L11 and L12 are outside the block and will be
run regardless the result of (num >= 60).
9. - sun13/04/2020 38PROG - Chapter 3: Branching 9
3.1b: Difference between = and ==
• Compile & run the program below and answer the
questions on the next page
10. - sun13/04/2020 38PROG - Chapter 3: Branching 10
Task Input Observation Explanation
1 Run the program y Display L10–12
and L14
As reply is y, it satisfies the if’s condition
(reply == 'y'). The program will then
enter the if block (L10-12) and run the
codes. It proceeds to run L14 after that.
Y and
Other
key
Display L14
only
As reply is not y, it fails to satisfy the if’s
condition (reply == 'y'). The program
will skip the if block (L10-12) and proceed to
run L14. As C is case-sensitive, y ≠ Y
2 Change == at L8
to =. Run and
compare result
to Task 1
y Same as before Logic error cannot be observed for this input
Y and
Other
key
Same display as
that when y is
entered
The program will run the if block when the
condition is true. As reply = 'y’ is an
assignment instead of a condition, the result
will be whatever it is assigned with. In this
case, it is 'y’ which is non-zero. Putting it as
the condition will always produce true.
Hence the if block will always run regardless
what key the user enters.
3.1b: Difference between = and ==
11. - sun13/04/2020 38PROG - Chapter 3: Branching 11
Task Input Observation Explanation
3 Change L8 from
reply == 'y’
to reply == y
- Error: ‘y’
undeclared
Without apostrophes, y is seen as a variable.
Hence the error.
With the above
change, declare
y as a char
y Display L14
only
Though reply is 'y’, we compare it with
variable y which does not contain the same
character. The condition reply == y is
therefore false. This is why the program skips
L10 – L12.
3.1b: Difference between = and ==
12. - sun13/04/2020 38PROG - Chapter 3: Branching 12
Indentation
• Notice that the codes within
braces {} are ‘pushed’ in?
• That’s what we call indentation
• It is done by using [Tab] key
• Program with indentation is
easier to read as it shows
clearly the blocks of codes
• Writing program without using
indentation is prone to error
Compare the two programs above,
which one is easier to read?
I have added some errors in both programs,
can you spot them?
13. - sun13/04/2020 38PROG - Chapter 3: Branching 13
Practical Exercise 3.1a: if structure
P3_1a.c
Write a program to allow users to enter their mark and checks
whether they fail or not. The passing mark is 50.
You may refer to the program ELA3_1a.c on page 7.
What if we want the program to display congratulate message to
those who pass? One way is to add another if statement. A
better way is to use if-else, which we are going to learn in the
next section.
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter your mark: 48
You have failed the test.
You must study harder!
14. - sun13/04/2020 38PROG - Chapter 3: Branching 14
if-else Statements
• if statement performs additional task
only when the condition is TRUE
if (condition)
{
// block of one or more C
// statements to be performed
// if the condition is true
}
• If-else statement performs one of two
additional tasks. One is when the condition
is TRUE, the other is when it is FALSE
if (condition)
{
// if the condition is TRUE
}
else
{
// if the condition is FALSE
}
cond?
Perform this
if condition
is TRUE
yes
no
cond?
Perform this
if condition
is TRUE
yes
no
Perform this
if condition
is FALSE
if
else
15. - sun13/04/2020 38PROG - Chapter 3: Branching 15
3.2a: if-else
Start
Prompt user to
enter mark
Get input mark
End
mark<50?
yes
no
Display
Congrat, pass
Display
Fail, study hard
Display
All the best
• Compile & run the program below and answer the
questions on the next page
16. - sun13/04/2020 38PROG - Chapter 3: Branching 16
Task Input Observation Explanation
1 Run the program 46 Display
L11, L12, L19
As mark is 46, it satisfies the if’s condition
(mark < 50). The program will then enter
the if block (L11, L12) and run the codes. It
proceeds to run L19 after that.
73 Display
L16, L17, L19
As mark is 73, it fails to satisfy the if’s
condition (mark < 50). The program will
then enter the else block (L16, L17) and run
the codes. It proceeds to run L19 after that.
3.2a: if-else
1. What is the range of marks that fall under if? What about else?
2. Student A scores 73 mark but accidentally enter -73 into this program. What
will happen? It will indicate that the student fail.
3. So what is the actual range of mark that fall under if? - ∞ to 49
4. Similarly Student B scores 45 mark but accidentally enter 455. What will
happen? It will indicate that the student pass
5. So what is the actual range of mark that fall under else? 50 to +∞
6. Is it possible to use only if-else to handle Case 2 and 4?
No. There are 3 conditions here. if-else only handle 2 opposing conditions.
17. - sun13/04/2020 38PROG - Chapter 3: Branching 17
Practical Exercise 3.2a,b: if-else structure
P3_2a.c
Improve the program in P3_1a.c to also output a message for those
who have passed the test as follows:
Reflection
What mistake did you make?
What have you learnt?
Check point:
P3_2b.c
Write a program to convert days to seconds. If the user input
negative value, display error message.
Rewrite P3_2b.c such that the if and else blocks are interchanged.
How should the if-condition be changed to achieve the same result?
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter your test mark: 70
Congratulations!
You have passed the test.
Enter your test mark: 45
You have failed the test.
You must study harder!
Enter the no. of days: 12
It is equal to 1036800 seconds.
Enter the no. of days: -2
Invalid input!
18. - sun13/04/2020 38PROG - Chapter 3: Branching 18
Practical Exercise 3.2c: if-else structure
P3_3c.c
In a factory, a worker is expected to work for 40 hours per week.
Any working hour that is beyond 40 hours will be entitled to an
overtime pay that is calculated at 1.5 times the pay rate.
Write a program to do the following:
• Prompt the user to enter the number of working hours for a
week and the pay rate for a worker.
• Calculate and print the pay that he will receive.
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter the number of hours worked in this week: 38
Enter the pay rate: 6.00
No overtime pay.
Total pay for the week is $228.00
Enter the number of hours worked in this week: 40
Enter the pay rate: 5.50
No overtime pay.
Total pay for the week is $220.00
Enter the number of hours worked in this week: 43
Enter the pay rate: 6.00
First 40-hour pay is $240.00
Overtime pay is $27.00
Total pay for the week is $267.00
19. - sun13/04/2020 38PROG - Chapter 3: Branching 19
Logical Operators
• How do you translate the following into C programming code?
- Customers who buy more than 4 tickets will be given a
discounted price of 8 dollars
- Senior citizens (older than 60) who buy more than 4
tickets will be given a discounted price of $6
• The example above has more than 1 conditions (Compound)
- So we need logical operators (i.e. &&) to combine them
• There are 3 logical operators as shown below
if (t > 4) {
p = 8.0;
}
if (a > 60 && t > 4) {
p = 6.0;
}
Logical Operators Function The logic of the compound statement is
c1 && c2 AND TRUE only if both c1 and c2 are TRUE
c1 || c2 OR TRUE if either c1 or c2 is TRUE
!c1 NOT The reverse of c1
21. - sun13/04/2020 38PROG - Chapter 3: Branching 21
Exercise: Logical Operators
Conditions Logical Expressions in C
1 x 0 or x 10 (x<=0 || x>=10)
2 age is between 18 and 21 inclusively (age>=18 && age<=21)
3 a, b, c must be all greater than 0 (a>0 && b>0 && c>0)
4 Lt is either 'A','B' or 'C' (Lt==‘A’ || Lt==‘B’ || Lt==‘C’)
5 Lt is from 'A' to 'J' or 'Z' ((Lt>=‘A’ && Lt<=‘J’)|| Lt==‘Z’)
6 a, b and c are all equal (a==b && a==c)
7 theta is not in the range of 0 to 180
inclusively
!(theta>=0 && theta<=180)
Alternative answer: (theta< 0 || theta>180)
8 N is not (less than 0 or greater than
100)
!(N<0 || N>100)
Alternative answer: (N >=0 && N <=100)
22. - sun13/04/2020 38PROG - Chapter 3: Branching 22
Exercise: Compound Conditions
Compound Conditions (Expressions) Which produces True?
1 ((a > 0) && (a < 180)) a:193 F a:47 T
2 ((a <= 0) ¦¦ (a >= 180)) a:-5 T a:126 F
3 !((a > 0) && (a < 180)) a:200 T a:84 F
4 ((m >= 0) && (m <= 100)) m:101 F m:0 T
5 ((m < 0) ¦¦ (m > 100)) m:-10 T m:38 F
6 ((a > 0) && (b > 0) && (c > 0)) a:1
b:2
c:0
F a:1
b:2
c:3
T
7 ((ag < 18) ¦¦ (ag > 60) && (sx == 'F')) ag:15
sx:‘F’
T ag:20
sx:’M’
F
8 ((ch == 'y') ¦¦ (ch == 'Y')) ch:’y’ T ch:’n’ F
9 ((ht > 0) && (ht < 20.0)) ht:20 F ht:9 T
23. - sun13/04/2020 38PROG - Chapter 3: Branching 23
Practical Exercise 3.3a: Logical operator &&
P3_3a.c: Enter and run the following program Questions
1. Change && to || in line 18, how
will the range be changed?
___________________________
___________________________
2. The angle that pass into the
trigonometric functions such as
cos() must be in _________
3. What is the formula to convert an
angle from degrees to radians?
___________________________
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter an angle (degrees): 30
cos(30) = 0.8660
Enter an angle (degrees): 95
Angle is not within range!
24. - sun13/04/2020 38PROG - Chapter 3: Branching 24
Practical Exercise 3.3b: Logical operator ||
P3_3b.c
In the previous program, the cosine value is calculated and
printed only when the angle is between 0
o
and 90
o
. Another
way of writing the program is to first check whether the angle is
OUTSIDE of the 0
o
to 90
o
range and then print the error
message. Otherwise (else) calculate and print the cosine value.
Modify program P3_3a.c
so that it uses the above
method to achieve the
same result.
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter an angle (degrees): 89
cos(89) = 0.017
Enter an angle (degrees): 91
Angle is not within range!
Enter an angle (degrees): 90
cos(90) = 0.0000
Enter an angle (degrees): 1
cos(1) = 0.9998
Enter an angle (degrees): 0
cos(0) = 1.0000
Enter an angle (degrees): -1
Angle is not within range!
25. - sun13/04/2020 38PROG - Chapter 3: Branching 25
if-else if Statement
• We use if - else if when we want to ensure that only one course of action
is chosen from multiple conditions (selections)
• Ended with else is optional
void main (void) {
int n;
float t, p;
printf(“Enter quantity:”);
scanf(“%d”, &n);
if (n >= 50) {
p = 12.0;
}
else if (n >= 10) {
p = 16.0;
}
else if (n >= 5) {
p = 18.0;
}
else {
p = 20.0;
}
t = n * p;
printf(“Total: %0.2f”, t);
}
cond1
Perform
Task 1
yes
no
cond2
Perform
Task 2
yes
no
cond3
Perform
Task 3
yes
no
Perform
Task 4
if
else if
else if
else
26. - sun13/04/2020 38PROG - Chapter 3: Branching 26
3.4a: if-else if
num<50
Display
Fail
yes
no
num<75
Display
Pass
yes
no
num<=100
Display
Merit
yes
no
Flowchart 1:
if- else if structure
num<50
Display
Fail
yes
no
num<75
Display
Pass
yes
no
num<=100
Display
Merit
yes
no
Flowchart 2:
if- if structure
Click here to
reveal answer
Click here to
reveal answer
27. - sun13/04/2020 38PROG - Chapter 3: Branching 27
3.4a: if - else if
1. Complete Flowchart 1 which is supposed to describe the if-else if part of
the program (L9 to L20)
2. Run the program. Enter 70. Explain why it does not display Fail and Merit.
• As num is 70, it fails to satisfy the condition (num<50), hence it will not display Fail
• Since the first condition is not met, the program moves on to check the next
condition (num<75). As it now satisfies the condition, it will display Pass.
• For else if structure, once a condition is satisfied, the program will skip
checking the rest of the conditions. Hence Merit will not be displayed.
3. Remove the else on L13 and L17 so that we will use if-if structure instead.
4. Run the program and enter 70. Compared to Task 2 and explain why it now
displays Merit.
• For if-if structure, the program will check every condition regardless of the result.
• So despite condition (num<75) is met, the program will proceed to check the next
condition (num<100). As 70 satisfies the condition, the program will display Merit.
5. With new understanding from Task 4, complete Flowchart 2 for if-if structure
6. Modify the conditions so that we can use if-if to accomplish the original task
• 2nd condition:(num>=50 && num<75)
• 3rd condition: (num>=50 && num<=100)
28. - sun13/04/2020 38PROG - Chapter 3: Branching 28
Practical Exercise 3.4a: if – else if
P3_4a.c
The following program prompts the user to enter his mark and prints
the grade according to the grading table below:
Questions
Will it work the same if we use
all if structure? Why?
Reflection
What mistake did you make?
What have you learnt?
Check point:
Type your mark: 82
Your mark is 82, grade A.
Bye-bye!!
80 ≤ mark ≤ 100 Grade A
70 ≤ mark < 80 Grade B
60 ≤ mark < 70 Grade C
50 ≤ mark < 60 Grade D
0 ≤ mark < 50 Grade F
Type your mark: 49
Your mark is 49, grade F.
Bye-bye!!
29. - sun13/04/2020 38PROG - Chapter 3: Branching 29
Practical Exercise 3.4b: if – else if
P3_4b.c
The final mark of a continuous assessment subject is based on the
MCQ (20%), the Practical Test PT (25%) and the Final Test FT (55%).
Write a program to do the following:
• Prompt the user for the marks of MCQ, practical test and final test.
• Calculate and print the final mark.
• Check the mark range and print a message as follows:
Reflection
What mistake did you make?
What have you learnt?
Check point:
Enter your MCQ, PT and FT marks: 40 50 60
Final mark: 54. Passed!
0 ≤ mark ≤ 50 Failed!
50 ≤ mark < 90 Passed!
90 ≤ mark ≤ 100 Distinction!
Enter your MCQ, PT and FT marks: 60 50 40
Final mark: 47. Failed!
Enter your MCQ, PT and FT marks: 80 90 95
Final mark: 91. Distinction!