You are on page 1of 19

BRANCHING and LOOPING

BRANCHING
What are Control flow statements?

 A program is set of instructions.


 By default these instructions are sequentially executed.
 Definition: The statements that transfers the control from one part of the program to another part of the
program ,with or without any condition is called as branching statements.

Types of Branching statements/Conditional statements/decision making statements/


Control construct
There are 2 types of branching statements present 1.Conditional Statement
2. Unconditional Statement.

1. Conditional Statement
 Definition: The statements that transfers the control from one part of the program to another part of the
program based on a condition is called as Conditional statements.
There are 5 Conditional statements in C

1. if control construct(simple if)


2. if else control construct
3. nested if else control construct
4. else if ladder or cascaded
5. switch control construct

The if statement (Simple if/ One way selection)


 An if statement is a single selection statement.
 It is used to execute a set of statements if the condition is true,
 If the condition is false, it skips executing those set of statements. Hence it is called one way selection.
Syntax: Flowchart:
Statement a1;
Statement a1; ……………
…….. Statement an;

Statement an;
if(condition)
{ if False
condition
Statement t1;
…………..
Statement tn; True
} Statement t1;
…………….
Statement b1; Statement tn;
……..
Statement bn;
Statement b1;
……………

Statement bn;
Explanation
 The keyword if must be followed by an expression and expression must be enclosed within parentheses.
 First statement a1 to an is executed sequentially(one after another).
 The if statement is executed next. The expression inside the parentheses is evaluated. i.e Condition is
checked, which results in either TRUE or FALSE .
 If condition is TRUE the statements t1 to tn are executed and then statements b1 to bn are executed.
 If condition is FALSE the statements t1 to tn are skipped and then statements b1 to bn are executed.

Advantage of if-statement
 Output of if-statement is true or false.
 if-statement is used as one way decision/selection statement.

Disadvantage

 If one action has to be performed when the condition is true and another action has to be performed
when the condition is false then if-statement is not recommended
 This disadvantage is overcome using two- way decision/selection statement called “ if-else statement”
An Example which illustrates if statement: To print given no is an even no.
Algorithm Flowchart Program

Algorithm: Check even number #include<stdio.h>


Input: A number void main()
Output: Even Number {
Step 1: Start int n;
Step 2: [input the number] printf(“ Enter the number\n”)
Read N scanf(“%d”,&n);
Step 3: [compute even number] if(n%2==0)
if n%2 is equals to zero {
Goto step 4 printf(“Even no”);
Otherwise goto step 5 }
Step 4: [display output]
Print “even no” }
Step 5: Stop

Note: Similarly write Algorithm, Flowchart and C Program for the following
i) To print given no is a odd no. Logic: if (n!=0)
ii) To print given no is a positive no. Logic: if(n>0)
iii) To print given no is a negative no.Logic: if(n<0)
The if – else statement (two way selection).
It is used to execute a set of statements if the condition is true, and another set of statements if the
condition is false. Hence it is called two way selection.

Syntax: Flowchart: Statement a1;


Statement a1; ……………
…….. Statement an;

Statement an;
if(condition)
{
if False
Statement t1; condition
………….. True
Statement tn;
} Statement t1; Statement E1;
……………. …………….
else
Statement tn; Statement En;
{ Statement E1;
………….. A
Statement En;
} Statement b1;
Statement b1; ……………

…….. Statement bn;


Statement bn;

Explanation
 The keyword if must be followed by an expression and expression must be enclosed within parentheses.
 First statement a1 to an is executed sequentially(one after another).
 The if statement is executed next. The expression inside the parentheses is evaluated. i.e Condition is
checked, which results in either TRUE or FALSE .
 If condition is TRUE the statements t1 to tn are executed and else block is skipped then statements b1 to
bn are executed.
 If condition is FALSE the statements if block is skipped and then statements E1 to En are executed and
then statements b1 to bn are executed.
An Example which illustrates if-else statement: To print given no is an even no or odd no.
Algorithm Flowchart Program

Algorithm: Check even number #include<stdio.h>


void main()
or odd no
{
Input: number n int n;
printf(“ Enter the number\n”)
Output: even Or odd
scanf(“%d”,&n);
Step 1: Start if(n%2==0)
{
Step 2:[Input Number]
printf(“Even no”);
Read n }
else
Step 3: if n % 2 is equals to 0
{
Print “even no” goto step 5 printf(“odd no”);
}
Otherwise goto step 4
Step 4: Print “odd no” }
Step 5: Stop

Note: Similarly write Algorithm, Flowchart and C Program for the following
i) To check given integer no is a positive no or negative no Logic: if(n>0) its positive else negative.
ii) To find largest of 2 no’s Logic: Let a and b be 2 no’s if(a>b) a is greater else b is greater

The nested if else control construct


 An if or if-else statement enclosed within another if or if-else statement is called Nested-if Statement.
 When an action has to be performed based on many conditions then Nested-if statement is used.

Syntax and Explanation


 The keyword if and else must be followed by an expression and expression must be enclosed within
parentheses.
 First statement a1 to an is executed sequentially.
 Condition 1 is checked if it is true then condition 2 is checked, if it is true block1 statements are
executed otherwise block2 statements are executed followed by statements b1 to bn.
 If condition 1 is false then block3 statements are executed followed by statements b1 to bn.
Syntax and Flowchart

Statement a1;
…….. Statement a1;
Statement an; ……………
if(condition 1) Statement an;
{
if (condition 2)
block 1;
False
else If condition
block 2; 1

} True
else
{ If condition False
block 3; 2
} True
Block 2
Statement b1; Block 3
Block 1
……..
Statement bn;

Statement b1;
……………
Statement bn;

An Example which illustrates if-else statement: To find biggest of three numbers.


#include<stdio.h>
void main()
{
int a,b,c;
printf(“ Enter the 3 numbers\n”)
scanf(“%d%d%d”,&a,&b,&c);
if(a>b)
{
if(a>c)
{
printf(“a largest”);
}
else
{
printf(“c largest”);
}
}
else
{
if(b>c)
{
printf(“b largest”);
}
else
{
printf(“c largest”);
}
}
}
Advantage: When an action has to be performed based on many decisions involving various types of
expressions and variables then nested if statement is used.
Disadvantage:
 Difficult to understand and modify.
 As depth of nesting increases, the readability of the program decreases.
Note: Flow chart refer class Notes

The else if ladder / Cascaded control construct


 An else-if ladder is a special case of nested if statement where nesting take place only in else part.
 It is used to execute one set of statements out of many set of statements depending up on the outcome of
the condition.
 Syntax, flowchart and explanation is given below

Explanation
 The keyword if and else must be followed by an expression and expression must be enclosed within
parentheses.
 First statement a1 to an is executed sequentially.
 First statement1 is executed followed by statement2.
 Condition 1 is checked
 if condition 1 is true control goes to Statement t1 to tn are executed and then statement b1 to bn
are executed.
 If condition 1 is false Condition 2 is checked
 if condition 2 is true control goes to Statement e1 to en are executed and then statement b1 to
bn are executed.
 If condition 2 is false condition 3 is checked
 If condition 3 is true control goes to Statement f1 to fn and are executed ,then followed by
statement b1 to bn.
 if condition 3 is false Statement g1 to statement gn are executed and then statement b1 to bn are
executed.
 No condition is specified for the else block
Syntax And Flowchart
Statement a1;
………….. Statement a1;
Statement an; …………..
Statement an;
if(condition 1)
{
Statement t1; True
……………. If condition
Statement tn; 1

Block 1 False
}
else if(condition 2) If condition False
{ 2
Statement e1; True
…………..
Block 2 If condition
Statement en; 3
} true false
else if(condition 3) Block 3 Block 4
{
Statement f1;
…………..
Statement fn; A
}
else
{ Statement b1;
Statement g1; ……………
……………
Statement bn;
Statement gn;
}
Block 1: Statement t1 …….. statement tn

Block 2: Statement e1 …….. statement en


Statement b1;
Block 3: Statement f1 …….. statement fn
…………
Statement bn; Block 4: Statement g1 …….. statement gn

An Example which illustrates else if ladder control statement:


1) To find biggest of three numbers. 2)to find grades depending on marks
Algorithm Program

Algorithm: To find largest of 3 numbers #include<stdio.h>


Input:3 numbers a,b,c void main()
Output: Largest number {
Step 1: Start int a,b,c;
Step 2: [Input 3 numbers] printf(“ Enter the 3 numbers\n”)
Read a,b,c scanf(“%d%d%d”,&a,&b,&c);
Step 3: if a is greater than b and a is greater than c if( a>b && a>c)
Print “a is largest” goto step 6 {
Otherwise goto step 4 printf(“a largest”);
Step 4: :if b is greater than a and b is greater than c }
Print “b is largest” goto step 6 else if( b>a && b>c)
Otherwise goto step 5 {
Step 5: Print “c is largest” printf(“b largest”);
Step 6: Stop }
else
{
printf(“c largest”);
}
}
Algorithm: Grading based on marks #include<stdio.h>
Input: A number mark
void main()
Output: Grade
Step 1: Start {
Step 2: [Input mark]
int marks;
Read marks
Step 3: if marks is greater than or equal to 80 printf(“ Enter the marks/n”);
print grade = ‘A’ ; goto step 7
if (marks >= 80)
otherwise goto step 4
Step 4: if marks is greater than or equal to 65 printf(“grade = ‘A’ ”);
print grade = ‘B’ ; goto step 7
else if (marks >= 65)
otherwise goto step 5
Step 5: if marks is greater than or equal to 50 printf(“grade = ‘B’ ”);
print grade = ‘C’ ; goto step 7
else if (marks >= 50)
otherwise goto step 6
Step 6: print grade = ‘D’ printf(“grade = ‘C’ ”);
Stop 7: Stop else
printf(“grade = D ”);
}
The Switch statement
Switch statements are used in following scenarios
 When a decision has to be made between many alternatives
 When the selection condition reduces to an integer value.
Definition: The switch statement is a control statement used to make a selection between many alternatives. i.e
multiple selection mechanism is implemented using switch.
 switch is alternative for two way selection multiple if-else-if.

Statement a1;
……………. Statement a1;
Statement an; …………….
Statement an;
switch(choice)
{
Choice/Expression
case value1: Block1;
break;
case 1 case 2 case 3 …..……
case n default
case value2: Block 2;
break;
case value3: Block3; Block 1 Block 2 Block 3 ……. Block n Block d
break;
default: Block d;
A
}
Statement b1;
…………….
Statement bn;
Statement b1;
…………….
Statement bn;

Explanation
 The switch statement is a multi-way decision that tests whether an expression matches one of a number
of constant integer values, and branches accordingly.
 Each case is labeled by one or more integer-valued constants or constant expressions.
 If a case matches the expression value, execution starts at that case.
 All case expressions must be different.
 The case labeled default is executed if none of the other cases are satisfied.
 A default is optional; if it isn't there and if none of the cases match, no action takes place. Cases and the
default clause can occur in any order.
 The break statement causes an immediate exit from the switch.
More about switch statement:
 The expression of a switch statement must result in an integral type, meaning an integer (byte, short, int,
long) or a char.
 The expression cannot be a Boolean value or a floating point value (float or double)
 No two case labels can have the same constant value.
An Example which illustrates switch control statement:
Program to simulate a simple calculator that performs arithmetic operations only on integers. Error message
should be reported if any attempt is made to divide by 0.

Algorithm Program

Algorithm: Simple calculator #include<stdio.h>


Input: Two Numbers void main()
Output: A number {
Step 1: Start int a,b,res;
Step 2:[Input 2 numbers] char choice;
Read a,b. printf(“ Enter your choice\n”);
Step 3: switch(choice) scanf(“%c”,&choicec);
{ printf(“ Enter two operands\n”);
case ‘+’: res = a+ b; scanf(“%d%d”,&a,&b,);
Output res; switch(choice)
break; {
case ‘-’: res = a- b; case ‘+’: res = a+ b;
Output res; printf(“%d”, res);
break; break;
case ‘*’: res = a-*b; case ‘-’: res = a- b;
Output res; printf(“%d”, res);
break; break;
case ‘/’: if(b==0) case ‘*’: res = a-*b;
{ printf(“%d”, res);
“Divided by 0 error” break;
} case ‘/’: if(b==0)
else {
{ printf(“error :Divided by 0”);
res = a/b; }
Output res; else
break; {
} res = a/ b;
printf(“%d”, res);
default: output “invalid op” }
} break;
default: printf( “invalid op”);
S4: Stop }
}

Advantages:
1. Improves readability of a program.
2. More Structured way of writing program.
Disadvantages:
1. Used only if the expressions used for checking results in integer value.
2. Cannot be used when a decision is based on range of values.

Unconditional Branch Statements


Definition:
The statements that transfer the control from one part of the program to another part without checking
for any conditions are called unconditional branch statements.
The 4 Unconditional branch statements are
1. goto
2. break
3. continue
4. return

The goto Statement


 goto is an unconditional branching statement, using which the control can be transferred from
one part of the program to another without any condition.
Syntax:
Statement a1;
…………….
Statement an;
goto label;
Statement b1;
…………..
Statement bn;
label: Statement c1;
…………..
Statement cn;

label statement : The label is a valid ‘C’ identifier followed by a colon. we can precode any statement by a
label in the form
Label : statement ;
This statement immediately transfers execution to the statement labeled with the label identifier.
Examples:
1. Program to print INDIA 5 times.

#include<stdio.h> OUTPUT: INDIA


void main() INDIA
{ INDIA
int i=1; INDIA
Back: printf(“INDIA\n”); INDIA
if(i!=5)
{
i++;
goto back;
}
}

2. Program to find sum of 10 natural numbers.


#include<stdio.h>
void main()
{
int i=0,sum=0;
top: if(i>10)
goto end;
sum=sum+i;
i++;
goto top;
end:printf(“sum=%d\n”,sum);
}

Disadvantages:
1. Using goto the code is difficult to read and understand.
2. Usage of goto results in unstructured programming i.e it is not a good programming style.

The break statement:


• The break statement is an unconditional jump statement.
• The break statement can be used as the last statement in each case's statement list.
• A break statement causes control to transfer to the end of the switch statement.
• If a break statement is not used, the flow of control will continue into the next case.
“What is a use of break statement?”

The break statement in C programming language has the following two usages:

• When the break statement is encountered inside a loop, the loop is immediately terminated and program
control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement.
• If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.

switch (option) for(… .......... )
{ {
case 'A': ……………….
aCount++; if(………….)
break; {
case 'B': ……
bCount++; break;
break; ……………..
case 'C': …………..
cCount++; }
break; ………….
} …………..
}
Example: Refer switch statement example program Example:
#include<stdio.h>
void main()
{
int i,n=5;
for(i=0;i<=n;i++)
{
if(i==3)
break;
printf(“%d\n”,i);
}
}

Output: 1 2

The continue Statement

 The continue statement can be placed only in the body of a for loop, a while loop, or a do...while loop.
 The continue statement is used only in the loops to terminate the current iteration and continue with
remaining iterations.
 In the while statement and do-while statement, whenever a continue statement is executed, the rest of
the statements within the body of the loop are skipped and the conditional expression in the loop is
executed.
 But, when continue is executed in the for loop ,control is transferred to expression 3.
 The pictorial representation is shown below:

Current iteration is skipped Current iteration is skipped Control is transferred exp3


do
{ for(exp1,exp2,exp3)
while(expression) Action 1; {
{ continue; Action 1;
Action 1; Action n; continue;
continue; Action n;
Action n; } while(expression); }
}
Example:
#include<stdio.h> Output: 1 2 4 5
void main()
{
int i,n=5;
for(i=1;i<=5;i++)
{
if(i==3)
continue;
printf(“%d\n”,i);
}
}

Example:

#include<stdio.h> OUTPUT: INDIA


void main() INDIA
{ INDIA
int i;
for(i=1;i<=3;i++)
{
printf(“INDIA\n”);
continue;
printf(“is our country\n”);
}
}

LOOPING
Looping constructs: Repetition (Looping constructs)
 A set of statements may have to be executed for a specified number of times or untill the condition is
satisfied(true) are called Looping Constructs.
 The statements that help us to execute a set of statements repeatedly are called Looping Constructs.
 It is implemented using the following statements.
 for
 while
 do-while
1. The while loop

Syntax Flowchart Example

Statement a1; #include<stdio.h>


Statement a 1; void main( )
Statement a2;
Statement a 2; {
initialization; int i;
i=1;
while(Condition check)
while(i<=5)
{ initialization
{
Statement b1;
printf(“INDIA\n”);
Statement b2;
i++;
updation; Condition false
}
} check

Statement c1;
true }
Statements c2;
Statement b1;
Statement b2; Output:
updation; INDIA
INDIA
INDIA
Statement c1;
INDIA
Statements c2;
INDIA

 Definition: A while loop is a looping statement which are used to execute a set of statements
repeatedly.
 Working:
 Statements a1 to an are executed in sequence.
 Condition is checked ,if it is true ,body of while loop, ie statements b1 to bn are executed.
 Thus the body of loop is repeatedly executed as long as the condition is true.
 Once the condition/expression is evaluated to false ,the control comes out of loop and statements
c1 to c n are executed.
 It is a pre testing loop and top testing loop and entry controlled loop.
2. The do while loop

Syntax Flowchart Example

Statement a 1; #include<stdio.h>
Statement a 1; void main( )
Statement a2;
{
Statement a 2;
initialization; int i;
i=1;
do
do
{ initialization {
Statement b1; printf(“INDIA\n”);
Statement b2; i++;
Statement b1;
updation; } while(i<=5);
Statement b2;
} while(Condition check); }
updation;
Statement c 1;

Statements c 2;
Output:
true
INDIA
Condition
check INDIA
INDIA
INDIA
false
INDIA
Statement c 1;

Statements c 2;

 Definition: A do while loop is a looping statement which are used to execute a set of statements
repeatedly.
 Since a set of statements have to be executed until a condition is true, it is also called condition
controlled loop
 The body of the loop is executed first and then the expression is evaluated to true or false. hence it is
called as post test loop/bottom testing loop
 As the expression is evaluated at the end ,the do while loop is also called as exit controlled loop.
 Syntax:
do and while are keywords.(also called reserved words).
 Working:
 Statements a1 to an are executed in sequence.
 First Statements inside the body of the loop is executed one after the other.
 Then the expression/condition is evaluated ,if it is true, body of the do while loop is executed.
 Thus the body of loop is repeatedly executed as long as the condition is true.
 Once the condition/expression is evaluated to false ,the control comes out of loop and statements
c1 to cn are executed.
 The moment expression is evaluated to false, the control comes out of the do while loop.
 The body of the loop is executed at least once before the condition is checked , hence it is
also called as post test loop .

3. The for loop

Syntax Flowchart Example


Statement A1; #include<stdio.h>
Statement A1; void main()
Statement A2;
{
Statement A2;
for (exp1 ;exp2; exp3) int i;
for(i=1; i<=5; i++)
{
Statement B1; false {
exp3 exp1
Statement B2; exp2
printf(“INDIA\n”);
} i++;
Statement C1; true }

Statements C2; }
Statement B1;
Statement B2;
Output:
INDIA
INDIA
Statement C1; INDIA
Statements C2; INDIA
INDIA

Definition
 A for loop is a control statement using which the programmer can give instructions to the computer to
execute a set of statements repeatedly for a specified number of times.

Explanation:
 First (exp1) is Initialization of the loop .
 Next (exp2) condition is checked. If condition is true then the control enters the body of the loop and
statements b1 to b2 are executed.
 After executing statements b1 to bn , control goes back and expression 3 (updation) is evaluated.
(exp3)updation of the loop is performed after which again the control goes back to the condition check,
if condition is true, the body is executed again.
 This process repeats as long as the condition evaluates to be true.
 Once the condition evaluates to be false, the control comes outside the body of the loop.

Difference between while loop and do while loop


while loops do while loops
pretest loop post test loop

Syntax Syntax

Statement a1; Statement a 1;


Statement a2; Statement a2;
initialization; initialization;
while(Condition check) do
{ {
Statement b1; Statement b1;
Statement b2; Statement b2;
updation; updation;
} } while(Condition check);
Statement c1; Statement c 1;
Statements c2; Statements c 2;

It is a top testing/entry controlled loop It is a bottom testing /exit controlled loop


since the condition is checked in the since the condition is checked in the
beginning itself. bottom of the loop.
It is a pre test loop, so if the expression is It is a post test loop,and the body of the
false in the beginning itself, the statements loop will be executed atleast once.
within the body of the loop will not be
executed.
While loop is a Entry controlled loop Do while loop is a Exit controlled loop the
,because the condition is checked first and body of loop will be executed first and at
if that condition is true than the block of the end the test condition is checked, if
statement in the loop body will be executed condition is satisfied then body of loop will
be executed again.

You might also like