Computer Programming: Decision Making in C If-Else Construct
Computer Programming: Decision Making in C If-Else Construct
Lecture 8
Decision making in C
if-else construct
1
Agenda
• Decision making
• Implementation in C
• if, if-else constructs
• Conditional statement
2
Decision making
• Till now, we have covered programs involving
sequential set of instructions
• However, in practice, many times, we want to
run a set of instructions for one condition and
another set of instructions for another
condition
• Essentially, we want a decision making
• Saying, If condition is true, do this else do that
3
Implementation in C
• Decision making is implemented in C using the
following three statements:-
– if statement
– if else statement
– Conditional statement
4
Part-1
if statement
if else statement
Conditional statement
5
if statement
• General Form:
Examples ?
6
Condition – true or false
• Condition expression in if statement evaluates
to either true or false
• Non-zero value is true and zero is false
eg.
if(4/3) is true and if(3/4) is false
7
Logical Operators
• Conditions can be combined using logical
operators
• Three logical operators are:-
– AND, &&
– OR, ||
– NOT, !
8
Operator Precedence (revisited)
• Logical and relational operators are added
• So, lets review the precedence !
9
Scope – if statement
• Default scope of if-statement is immediately
next statement after if condition
• If more than one statements are to be
executed within an if-statement then
{ } are to be used
10
Multiple if statements
• There can be multiple if-statements within a
single if-statement
• Example:-
if (condition1)
if (condition2)
if (condition3)
…. so on
11
Part-2
if statement
if else statement
Conditional statement
12
if else statement
• Can we execute a set of statement if the
condition is NOT satisfied ?
• Yes, after the else keyword
• Statements after the if belong to if-block and
after the else belong to else-block
• Default scope of else statement is statement
immediately after else
– So, to execute more than one statement in else
block, use { }
13
Nest if-else
• Entire if-else construct can be placed within
– if block
– else block
• No limit to nesting
• Please do proper indenting
– Helps in readability of program
14
Part-2
if statement
if else statement
Conditional statement
15
Conditional operator
• Also called as ternary operator
• Two operators ( ? and : ) are involved with
three operands
• General form:
expression1 ? expression 2 : expression 3
• If expression 1 is true, then value returned will
be expression 2 else expression 3
16
Questions
17