CSC113-Programming Fundaments
Lecture 07
Week 05
Ms. Noor-ul-Huda
Lecturer
Department of Computer Science
College of Computer Science and Information Systems
[email protected]
Lecture outcomes:
◦ Conditional Statements
If
If-Else
matching else
Switch
default
break
Decision Making
◦ Decision-making statements decide the direction and the flow of the
program.
◦ They are also known as conditional statements because they specify
conditions with Boolean expressions evaluated to a true or false Boolean
value.
If the condition is true, a given block of code will execute;
if the condition is false, the block will not execute.
Need of Conditional
Statements
Conditional Statements in C:
◦ Control structures that execute different code blocks based on conditions.
Reasons for Using Conditional Statements:
◦ Branching: Different paths based on conditions.
◦ Control Flow: Order of statement execution control.
◦ Handling Different Cases: Handling specific conditions.
◦ Event-Driven Programming: Responding to user interactions with specific code.
Conditional Statements
•For the computer to make decisions, must be able to test CONDITIONS
◦ IF it is raining
◦ THEN I will not go outside
◦ IF Count is not zero
◦ THEN the Average is the Sum divided by the Count
•Conditions specified using logical data
Logical Data in C
ono explicit logical type
oint and char values can be treated as logical values
otwo possible logical values
o 0 or ‘\0’ - false
o anything else - true
ospecific operators produce logical values
Logical Expressions
•Relational operators:
• operators to compare two values
• syntax: expr1 relop expr2
• expressions must be of the same type (any)
•Logical operators:
• operators to logically combine logical values
• produce complex combinations of conditions
• operators apply to logical values
Relational Operators
Operator Meaning
X == Y X equal to Y
X != Y X not equal to Y
X < Y X less than Y
X > Y X greater than Y
X <= Y X less than or equal to Y
X >= Y X greater than or equal to Y
Relational Examples
A: 4 B: 3 C: 2.5
A < B 0 (false)
‘A’ < ‘B’ 1 (true)
When chars compared, ASCII codes compared
‘A’ != ‘a’ 1 (true)
Note, expressions must be of same type
But, implicit conversions will be done
B > C 1 (true), B converted to float
Combined Expressions
Complex combinations of operations can be used:
4<3+2
4< 5
1 (true)
Why isn’t expression evaluated as (4 < 3) + 2?
Relational operators have lower precedence than arithmetic operators, higher than assignment
Have left-associativity
Operator Precedence
> < >= <= 10
= != 9
Logical Operators
Simple (relational) logical expressions true or false depending on values compared
Compound logical expressions built out of logical combinations of simple expressions
Examples:
“I am standing in a lecture hall AND
the moon is made of green cheese”
is false, but
“I am standing in a lecture hall OR
the moon is made of green cheese”
is true
Logical Expression
Syntax:
LogExpr1 LogicalOp LogExpr2 (&& ||)
LogicalOp LogExpr (!)
(2 < 3) && (17 != 29) /* && - AND */
1 && 1 /* true AND true */
1 /* true */
Decision Making
Problem: input two numbers and store the largest in Big
Num1: 17 Num2: 53 Big: 53
Algorithm
1. Input Num1 and Num2
2. Store largest of Num1 and Num2 in Big
2.1 Store Num1 in Big
2.2 IF Num2 > Num1 THEN store Num2 in Big
IF Statement
Syntax: if (LogicalExpr) Statement
Program context:
statement1;
if (LogicalExpr) statement2;
statement3;
Order of execution:
LogicalExpr
1 (true) 0 (false)
statement1 statement1
statement2 statement3
statement3
Flow of Execution
statement1
Logical true
statement2
Expression
false
statement3
Flow Chart for our Problem
input Num1
input Num2
Store Num1 in Big
true
Num2 > Num1 Store Num2 in Big
false
Code for Solution
int findMax(int Num1, int Num2) {
int Big;
Big = Num1;
if (Num2 > Num1) Big = Num2;
return Big;
}
Trace of Solution
Trace of findMax(9,6):
Num1 Num2 Big
statement 9 6 ?
Big = Num1; 9
if (Num2 > Num1)
return Big;
Statement in If
Any statement reasonable as the single statement in if
◦ expression statement
◦ assignment statement
◦ function call (printf, scanf, etc.)
◦ compound statement
◦ if statement
If-Else Statement
Syntax:
if (LogicalExpr)
StatementA
else
StatementB
false Logical true
statementB statementA
Expression
Using If-Else for Robustness
float calcAverage(float sum,
int count) {
if (count == 0)
return 0.0;
else
return sum / count;
}
Note return statement for each condition
Compound Statements and If-
Else
if ((year % 4) == 0) {
printf(“Leap year\n”);
numDays = 366;
}
else {
printf(“Not a leap year\n”);
numDays = 365;
}
Programming Tip: Compound
Stmt
Does not hurt to always use compound statements for if, if-else statements
if (LogicalExpr) {
/* statement or statements */
}
if (LogicalExpr) {
/* statement(s) */
}
else {
/* statement(s) */
}
Easy to add statements later
Programming Tip: Indenting
Use indenting to make code more clear
◦ indent statements in function definition to clearly identify body of function
◦ indent statement(s) executed for if by fixed amount (2,3 chars) every time
◦ for ifs within an if indent further
◦ indent else statements(s) similarly
◦ may want to make {,} match (on separate lines)
Programming Tip: Conditions
Code most likely conditions first
Code positive conditions where possible
Code parts of solution executed most often first
Multiway Selection
Multiway if more than 2 alternatives
Example:
Student Score Message
0-55 Failing
56-65 Unsatisfactory
66-100 Satisfactory
If-Else has two alternatives, to do multiway, string together If-Else statements
Multiway Flow Chart
Score true
Failing
<= 55
false
Score true
Unsatisfactory
<= 65
false
Satisfactory
Multiway with If-Else
if (score <= 55)
printf(“Failing\n”);
else
if (score <= 65)
printf(“Unsatisfactory\n”);
else
printf(“Satisfactory\n”);
Indenting If-Else Combinations
Multiway if-else statements sometimes indented:
if (score <= 55)
printf(“Failing\n”);
else if (score <= 65)
printf(“Unsatisfactory\n”);
else
printf(“Satisfactory\n”);
Rule for else: else matches most recent if
Conditions Checked in
Reverse
Score true
Satisfactory
> 65
false
Score true
Unsatisfactory
> 55
false
Failing
Ordering Conditions
if (score > 65)
printf(“Satisfactory\n”);
else if (score > 55)
printf(“Unsatisfactory\n”);
else
printf(“Failing\n”);
But must check conditions in correct order
if (score > 55)
printf(“Unsatisfactory\n”);
else if (score > 65)
printf(“Satisfactory\n”);
else
printf(“Failing\n”);
Score of 70 would produce “Unsatisfactory”
Multiway with If Statements
Possible but inefficient:
if (score <= 55)
printf(“Failing\n”);
if ((score > 55) && (score <= 65))
printf(“Unsatisfactory\n”);
if (score > 65) printf(“Satisfactory\n”);
Program Robustness
Example assumes score in interval [0,100] but doesn’t check
Add test:
if ((score >= 0) && (score <= 100))
/* print message */
else
printf(“Bad score: %d\n”,score);
Completed Code
if ((score >= 0) && (score <= 100)) {
if (score <= 55)
printf(“Failing\n”);
else if (score <= 65)
printf(“Unsatisfactory\n”);
else
printf(“Satisfactory\n”);
}
else
printf(“Bad score: %d\n”,score);
Nesting Example
if (A > 0) false true
A>0
if ((A % 2) == 0)
S1 = S1 + A;
(A % 2)
else A == 0
== 0
S2 = S2 + A; true
false true false
else
NS = S2 = S1 =
printf
if (A == 0) NS + A S2 + A S1 + A
printf(“A zero\n”);
else printf("All done")
NS = NS + A;
printf(“All done.\n”);
Choosing Conditions
Selection Example C Statement
One way X>0 If
Two way X>0 If-Else
X <= 0
Multiway 0 <= X <= 10 Nested
11 <= X <= 20 If-Elses
21 <= X <= 30
Switch Statement
More readable approach: switch statement
switch (score) {
case 9: case 10:
grade = ‘A’;
break;
case 7: case 8:
grade = ‘B’;
break;
case 5: case 6:
grade = ‘C’;
break;
case 0: case 1: case 2: case3: case 4:
grade = ‘F’;
}
Switch Format
switch (Expression) {
case const1-1: case const1-2: ...
statement
statement
...
case const2-1: case const2-2: ...
statement
statement
...
default: ...
statement
statement
...
}
Switch Rules
Expression must be integral type (no float)
Case labels must be constant values
No two case labels with same value
Two case labels can be associated with same set of statements
Default label is not required
At most one default label
Switch Rules
Evaluating
◦ determine value of expression
◦ look for corresponding label
◦ if no corresponding label look for default
◦ if no corresponding label or default, do nothing
◦ execute all statements from label to }
ALL statements from label to } ???
Executing Switch Example
switch (score) {
score is 7:
case 9: case 10:
grade = ‘B’
grade = ‘A’;
grade
case =7:
‘C’case 8:
grade = ‘B’;
case 5: case 6:
score is 5:
grade = ‘C’;
}
grade = ‘C’
score is 9:
gradequite
not = ‘A’ what we want
grade = ‘B’
grade = ‘C’
The break Statement
•break used to indicate a set of statements is finished (and no more should be executed)
•syntax: break;
•break says to stop executing and go to the next } (skipping any statements in between)
•add after each set of cases
default case
The default case can be used to deal with robustness issues
(score is < 0 or > 10)
switch (score) {
case 9: case 10:
grade = ‘A’;
break;
case 7: case 8:
grade = ‘B’;
break;
case 5: case 6:
grade = ‘C’;
break;
case 0: case 1: case 2: case3: case 4:
grade = ‘F’;
break;
default:
printf(“Bad score %d\n”,score);
}
Other Expression Types
Any integral type can be used as expression
Cases must match
char married;
switch (married) {
case ‘S’: case ‘s’:
printf(“single”); break;
case ‘D’: case ‘d’:
printf(“divorced”); break;
case ‘M’: case ‘m’:
printf(“married”);
}
When Not to Use Switch
Example: Case 0 <= X <= 100
switch (x) {
case 0: case 1: case 2: case 3:
case 4: case 5: case 6: case 7:
…
case 100:
…
}
Better to use nested ifs