Control Statements in C
Control Statements
• To decide what should be the flow of the execution of the program.
• To execute bunch of statements from code.
C provides three styles of flow control :
• Selection
• Branching
• Iteration/Looping
Selection Statements
By using these statements ,we can choose one branch or another.
Following are the different Selection statements :
• if
• if else
• else if ladder
if Statement
• Most simple form of the branching statements.
• If the expression is true then the statement or block of -
statements gets executed otherwise these statements are
skipped.
Syntax :
if(condition)
{
Block of Statements
}
if else Statement
• If the condition evaluates to true, then the if block of code will be executed, otherwise
else block of code will execute.
Syntax :
if(condition)
{
Block of if Statements
}
else
{
Block of else Statements
}
else if ladder statement
• An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions.
Syntax : if(condition 1)
{
Block of if Statements
}
else if(condition 2)
{
Block of else if-1 Statements
}
else if(condition 3)
{
Block of else if-2 Statements
}
else
{
Block of else Statements
}
Branching Statement-switch case
• If a programmer has to choose one among many alternatives if...else can be used but, this makes
programming logic complex.
• In switch...case, expression is either an integer or a character
• If the value of switch expression matches any of the constant in case, the relevant codes are executed and
control moves out of the switch case statement.
• If the expression doesn't matches any of the constant in case, then the default statement is executed.
Syntax : switch (expression)
{
case constant1:
break;
case constant2
break;
. . .
default:
break; }
Iterative/Looping Statements
Loops are used in performing repetitive work in programming.
There are 3 types of loops :
• while loop
• do while loop
• for loop
While Loop
Syntax :
Initialization;
while (condition)
{
statements to be executed.
Increment/ decrement;
}
Do-While Loop
Syntax :
Initialization;
do
{
some code/s;
Increment/ decrement;
}while (condition);
For Loop
Syntax :
for(initialization ; condition ; incre/ decre)
{
code/s to be executed;
}
Objectives
At the end of this session you will understand :
Need of Control Statements
• Selection(if, if-else, else if ladder)
• Branching(switch case)
• Looping(While, do while, for)