Chapter 4-Decision Making and Branching in C Programs
Chapter 4-Decision Making and Branching in C Programs
2
These statements are:
1. if statement.
2. if else statement.
3. else if statement.
4. switch statement.
3
4.1 if statement:
•Used to execute an instruction (either simple
or compound) depending on the result of a
condition.
Syntax:
if ( condition)
{ simple or compound statement;
}
If the result of (condition) is true, the statement
will execute, otherwise it will not.
No need to use { } in case if it works on only one
simple statement. 4
Flowchart of if statement.
5
6
7
8
4.2 if else statement:
•In if statement, if the condition returns
false then no statement will be executed.
•This problem is handled in if else
statement where two statements are
written for both results of the condition
i.e. for True and False.
9
Syntax:
if (condition)
{ simple or compound statement1;
}
else
{simple or compound statement2;
}
If the result of (condition) is true, statement1
will execute, otherwise statement2 will
execute.
No need to use { } in case if or else works on
only one simple statement. 10
Flowchart of if else statement.
11
12
13
14
15
16
17
4.3 else if statement:
-Used to check multiple conditions.
18
Syntax:
if (condition1)
{ simple or compound statement1;
}
else if (condition2)
{simple or compound statement2;
}
........
else
{ default simple or compound statement;
}
19
•Starting from the top, the program will
check the conditions.
•If any condition is True the statement
after it will be executed, and all other
statements will be neglected.
20
Flowchart of nested else if statement.
21
22
23
24
25
26
27
4.4 switch statement:
• It is also used to check multiple conditions
in order to select one case only out of a
number of cases.
• It is used in programs as a replacement of else
if. But, it has two limitations:
32
33
34
35
36
37
38