10
Decision Making What you’ll learn: 1. If else 2. Ternary Operators 3. Switch case

2.decision making

Embed Size (px)

Citation preview

Page 1: 2.decision making

Decision Making

What you’ll learn:

1. If else

2. Ternary Operators

3. Switch case

Page 2: 2.decision making

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.

Page 3: 2.decision making

Control Statements

Types of control statements:

Decision Making Statements

Iterative Statements

Jump Statements

Page 4: 2.decision making

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

Page 5: 2.decision making

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

Page 6: 2.decision making

If – else

Syntax:

if (expression) {

…block of statement(s)…

}

else {

…block of statement(s)…

}

expression

instructions instructions

True False

Page 7: 2.decision making

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

Page 8: 2.decision making

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

Page 9: 2.decision making

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

Page 10: 2.decision making

Ternary Operator

Syntax:

test_condition ? statement1 : statement2 ;

Equivalent form in if-else construct:

if (test_consition)

statement1;

else

statement2;

expression

instruction instruction

True False