Fe1008 06
Fe1008 06
1. Sequence
FE1008 Computing Statements are executed line by line in
sequential order.
2. Selection
Chapter 6 Sequence of program execution may be altered
based on some conditions.
Decision Making 3. Repetition
A group of statements is repeated a certain
number of times.
6-2
Note: Note:
Do not confuse == with = (assignment) In C, any non-zero numeric value can also
a==b Checks whether values of a and b are represent TRUE.
equal.
Example:
a=b Value of b is assigned to a. There is change
of data. a = 15;
Suppose a = 1, b = 5 if (a) printf("%d", a);
printf("The value of a==b is %d", a==b); As a is not zero, printf() will be executed.
printf("The value of a=b is %d", a=b);
If a is 0 (which means FALSE), printf() will
not be executed.
6-7 6-8
Note: Remark on the example about isdigit()
Original Form:
Suppose we write the statement as
if (a = 15) printf("%d", a); char ch='1';
if (isdigit(ch) != 0)
Interpretation: printf("%c is a digit.", ch);
else
Value of expression a = 15 is 15. printf("%c is not a digit.", ch);
Expression Value
Characters can be compared using relational
operators.
'9' >= '0' 1 (TRUE)
Is 'B' > 'A'? (57) (48)
Is '1' > 'A'? 'B' <= 'A' 0 (FALSE)
Basis for comparison?
'A' <= 'a' 1 (TRUE)
ASCII values
(65) (97)
'a' <= '$' 0 (FALSE)
6-11 6-12
Logical Operators (&&, ||, !) Examples
AND, OR, NOT
temperature > 90.0 && humidity > 0.9
Symbols && || !
x >= 1 || x < 0
These are needed to form complex conditions.
They increase the decision-making capabilities x >= 1 && x < 0 (possible?)
of our C programs. !(x >= 1 && x < 0) (True or false?)
&& and || are binary operators because they 'A' <= ch && ch <= 'Z'
act on 2 expressions.
! is unary.
6-13 6-14
6-19 6-20
Exercises: Nested if statements
6-21 6-22
Exercise Exercise
• Rewrite the above so that the program tests Suppose we rewrite this program fragment in
for 'F' grade first, then 'D', etc. the form:
• Suppose we rewrite Program Fragment 6.4 if (quiz_mark < 50) grade = 'F';
using separate if statements: if (quiz_mark >= 50) grade = 'D';
if (quiz_mark >= 80) grade = 'A'; if (quiz_mark >= 60) grade = 'C';
. . .
if (quiz_mark >= 70) grade = 'B';
if (quiz_mark >= 60) grade = 'C'; What's the difference?
Is it equivalent to the original if-else-if...
. . . . . .
form?
Are the 2 ways of writing equivalent?
6-27 6-28
Program 6.5 Program 6.5 (Continued)
[A] Voltage [B] Current [C] Resistance printf("Your selection => ")
scanf("%c", &selection);
Your Selection (A, B, C) =>
6-29 6-30
6-33 6-34