This document discusses different methods for decision making and controlling the flow of a program, including if/else statements, ternary operators, and switch/case statements. If/else statements allow for executing one block of code if a condition is true and another if it is false. Ternary operators provide a shorthand for if/else in a single line. Switch/case allows evaluating an expression and executing different code blocks based on matching cases. Together, these control structures allow programs to have multiple conditional paths and choose between them.
2. Flow of a Program
Start
set of instructions
…
set of instructions
Stop
Program executes
instructions sequentially.
Normal flow of a program
shows a single path.
3. Control Statements
Types of control statements:
Decision Making Statements
Iterative Statements
Jump Statements
4. What if you want to have multiple paths?
Start Path - 1
Path - 3
Stop
Path – 1
Path - 3
Path – 2
And need to choose one among them based on some condition?
Path Some Condition
5. The Solution: Decision Making
Deciding the order or flow of execution of statements is called decision making
Decision making statements in C are:
If – else
Ternary Operator
Switch
6. If – else
Syntax:
if (expression) {
…block of statement(s)…
}
else {
…block of statement(s)…
}
expression
instructions instructions
True False
7. Nested if - else
Syntax:
if (expression1) {
…block of statement(s)…
}
else {
if (expression2) {
…block of statement(s)…
}
else {
if (expression3) {
…block of statement(s)…
}
else {
…block of statement(s)…
}
}
}
exp-1
exp-2
instructions instructions instructions
True
TrueFalse
False
8. else-if ladder
Syntax:
if (expression1) {
…block of statement(s)…
}
else if (expression2) {
…block of statement(s)…
}
else if (expression3) {
…block of statement(s)…
}
….
….
else {
…block of statement(s)…
}
exp-1
…
exp-n
True
True
True
False
False
False
(else)
Set of instructions
Set of instructions
Set of instructions
Set of instructions
Set of instructions
9. Switch-case
Syntax:
switch (case_expression)
{
case constant_expression1 :
…block of code…
break;
case constant_expression2 :
…block of code…
break;
case constant_expression3 :
…block of code…
break;
…
default : … block of code…
}
exp-1
…
Default
True
True
True
False
False
False
Set of instructions
Set of instructions
Set of instructions
Set of instructions
10. Ternary Operator
Syntax:
test_condition ? statement1 :
statement2 ;
Equivalent form in if-else
construct:
if (test_consition)
statement1;
else
statement2;
expression
instruction instruction
True False