Upload
hardik-gupta
View
44
Download
0
Embed Size (px)
Citation preview
Decision Making
What you’ll learn:
1. If else
2. Ternary Operators
3. Switch case
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.
Control Statements
Types of control statements:
Decision Making Statements
Iterative Statements
Jump Statements
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
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
If – else
Syntax:
if (expression) {
…block of statement(s)…
}
else {
…block of statement(s)…
}
expression
instructions instructions
True False
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
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
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
Ternary Operator
Syntax:
test_condition ? statement1 : statement2 ;
Equivalent form in if-else construct:
if (test_consition)
statement1;
else
statement2;
expression
instruction instruction
True False