Chapter - 6 Looping
Chapter - 6 Looping
Chapter – 6
Looping
Chapter – 6 : Looping
Introduction
In this chapter, we will discuss
Need of looping
infinite loop.
Chapter – 6 : Looping
Need of Looping
Allow you to efficiently use variables
It can input, add, and average multiple numbers using a
limited number of variables
Example:
Add Five Numbers
Chapter – 6 : Looping
Loop Control Structures
Loop Structure
Chapter – 6 : Looping
Loop Control Structures
Entry Controlled Loop Exit Controlled Loop
Chapter – 6 : Looping
Loop Control Structures
Chapter – 6 : Looping
Loop Control Structures
Loops
Chapter – 6 : Looping
Entry Controlled Loop-while loop
The while loop is the simplest looping structure
In the while loop ,the given expression will be check at the time of the loop entry,
if given expression becomes true then control will transfer into the loop body.
The counter value will be modified and again given expression will be checked to
enter in to the loop.
This process will continue until the given expression become false.
The while loop contains only expression part ,initialization will be done before
the while loop
Chapter – 6 : Looping
Entry Controlled Loop-while loop
Syntax Example
Chapter – 6 : Looping
Entry Controlled Loop-while loop
/* program to print multiplication table using while loop. */
void main()
{
int n, i, ans;
clrscr();
int a =1 ;
While (a <=5) // 1<=5 stands true
{
printf(“%d ”,a); // print 1
a++; // a=2
}
Output : 1 2 3 4 5
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Syntax
for ( initialization ; condition ; inc/dec)
{
// loop body
}
Chapter – 6 : Looping
Entry Controlled Loop-for loop
For loop contains three different parts: initialization, condition
and inc/dec part.
When the loop executes for the first time, initialization of the
counter variable will be done after that expression given into the
condition part is tested, if test expression evaluate to true, control
will enter into the loop body.
After that control will transfer to the third part where counter
value will be either incremented or decremented.
With the modified counter value test expression will be check again
to enter into the loop.
Chapter – 6 : Looping
Entry Controlled Loop-for loop
This process will be repeated until condition becomes false.
Once the condition becomes false, the loop will be skipped and
statement following by for loop will be executed.
We can also skip any of the part of the loop as per our requirement.
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Example :
1 4
for(i=0;i<5;i++)
2
{
printf(“i= %d\n” , i); 3
}
printf(“After loop , i= %d\n” , i);
Chapter – 6 : Looping
Entry Controlled Loop-for loop
void main()
{
int n, i, ans;
clrscr();
Chapter – 6 : Looping
Entry Controlled Loop-for loop
Note
A for loop is used when a loop is to be executed a known
number of times. We can do the same thing with a while
loop, but the for loop is easier to read and
more natural for counting loops.
Chapter – 6 : Looping
Additional features of for loop
1. p=1;
Chapter – 6 : Looping
Additional features of for loop
6. m=5;
Initialization and inc/dec section can be
for(;m!=100;)
omitted. (Initialization can done before
{ the for statement and inc/dec can be done
inside the body loop)
printf(“%d\n”,m);
m=m+5;
}
7. for(j=1000;j>0;j=j-1) • Loop is executed 1000 times without producing any
output; it simply causes time delay.
; • Body of the loop contains only a semicolon, known as
null statement
Chapter – 6 : Looping
Exit Controlled Loop-do..while loop
An Exit Control Loop checks
the condition for exit and if
given condition for exit evaluate
to true, control will exit from
the loop body else control will
enter again into the loop.
Chapter – 6 : Looping
Exit Controlled Loop-do…while loop
Do …while loop is an exit control loop.
If the condition for the exit becomes true then loop will be
terminate otherwise it will be executed for the next time.
Chapter – 6 : Looping
Exit Controlled Loop-do…while loop
Syntax
do
{
//loop body
} while (expression);
Example
do
{
printf("\n Value of I is %d", i) ;
i++ ; // modify counter value
} while( i <= 10);
Chapter – 6 : Looping
Exit Controlled Loop-do…while loop
Comparision of While and Do..While Loop :
int main()
{
bool a=true;
Chapter – 6 : Looping
Exit Controlled Loop-do..while loop
void main() switch(choice)
{ {
float x, y, ans; case 1:
int choice; ans = x + y;
break;
case 2:
do ans = x - y;
{ break;
case 3:
printf("\n1.Addition\n2.Subtractio ans = x * y;
n\n3.Multiplication\n4.Division\n break;
5.Exit); case 4:
printf("\nEter Your Choice:"); ans = x / y;
break;
scanf("%d", &choice);
case 5:
exit(0);
if(choice!=5) default:
{ printf("\n Invalid choice!");
printf("\n Enter X and Y: " ); }
printf("\n Answer is %.2f", ans );
scanf("%f %f", &x, &y);
getch();
} } while(choice!=5)
}
Chapter – 6 : Looping
Exit Controlled Loop-do…while loop
The Do… While Loop :
Example :
int main() Output
{
int a = 1 ;
do
{
printf ( "Hello World\n" ) ;
a ++ ;
} while ( a <= 10 ) ;
return 0;
}
Chapter – 6 : Looping
WHILE LOOP DO…WHILE LOOP
It does not have semicolon (;) at the end of In do while loop semicolon (;) at the end of
the expression. the expression is compulsory.
Syntax:
do
while(condition)
{
{
// loop body
// loop body
} while(condition);
}
Example:
do
while(i<=5)
{
{
printf(“\n%d”,i);
printf(“\n%d”,i);
i++;
i++;
} while(i<=5) ;
}
Chapter – 6 : Looping
Use of sentinel values
Sentinel Value :
A sentinel value (also referred to as a flag value, trip
Chapter – 6 : Looping
Use of sentinel values
Sentinel Value :
Example :
printf(“Enter Count ( Or -1 to quit)”);
scanf(“%d”,count);
int max=count;
while(count != -1 )
{
if (count > max)
max=count;
printf(“Enter Count ( Or -1 to quit)”);
scanf(“%d”,count);
}
Chapter – 6 : Looping
Use of sentinel values
if (max > -1)
{
printf(“Maximum is : %d “ , max);
}
else
{
printf(“No Count Entered …”);
}
Chapter – 6 : Looping
Use of sentinel values
Suppose you want to find the maximum of the data entered
from the keyboard.
Chapter – 6 : Looping
Nesting of looping statements
A loop inside another loop is called a nested loop.
The depth of nested loop depends on the complexity of a
problem.
We can have any number of nested loops as required.
Consider a nested loop where the outer loop runs n times
and consists of another loop inside it.
The inner loop runs m times.
Then, the total number of times the inner loop runs during
the program execution is n*m.
Chapter – 6 : Looping
Nesting of looping statements
Chapter – 6 : Looping
Nesting of looping statements
1. Nested while loop :
A while loop inside another while loop is called nested while
loop.
Syntax :
while (condition1)
{
statement(s);
while (condition2)
{
statement(s);
}
}
Chapter – 6 : Looping
Nesting of looping statements
1. Nested while loop :
Example of Nested while loop : C program to print the
number pattern.
Output :
Chapter – 6 : Looping
Nesting of looping statements
In this program, nested while loop is used to print the pattern.
The outermost loop runs 5 times and for every loop, the
innermost loop runs i times which is 1 at first, meaning only "1"
is printed, then on the next loop it's 2 numbers printing "1 2"
and so on till 5 iterations of the loop executes, printing "1 2 3 4
5".
Chapter – 6 : Looping
Nesting of looping statements
2. Nested do-while loop :
A do-while loop inside another do-while loop is called
do
{
statement(s);
do {
statement(s);
}while (condition2);
}while (condition1);
Chapter – 6 : Looping
Nesting of looping statements
2. Nested do-while loop :
Example : C program to print the given star pattern.
Output :
Chapter – 6 : Looping
Nesting of looping statements
In this program, nested do-while loop is used to print the star
pattern.
The outermost loop runs 5 times and for every loop, the
innermost loop runs i times which is 1 at first, meaning only
one "*" is printed, then on the next loop it's 2 printing two stars
and so on till 5 iterations of the loop executes, printing five
stars.
Chapter – 6 : Looping
Nesting of looping statements
3. Nested for loop :
A for loop inside another for loop is called nested for loop.
Syntax :
Chapter – 6 : Looping
Nesting of looping statements
3. Nested for loop :
Chapter – 6 : Looping
Nesting of looping statements
3. Nested for loop :
Example : C program to print all the composite numbers
Chapter – 6 : Looping
Nesting of looping statements
A number is said to be composite if it has at least one factor
other than 1 and itself.
The outer for loop runs from 2 to n and the inner loop is
used to determine whether a number is composite or not.
Chapter – 6 : Looping
Nesting of looping statements
Note
There can be mixed type of nested loop i.e. a for loop
inside a while loop, or a while loop inside a do-while loop.
Chapter – 6 : Looping
Use of Break & Continue
It is sometimes desirable to skip some statements inside
the loop or terminate the loop immediately without
checking the test expression.
break Statement ::
The break statement terminates the loop (for, while and
break;
Chapter – 6 : Looping
Use of Break & Continue
Flowchart of break statement
Chapter – 6 : Looping
Use of Break & Continue
Example :
int main()
{
int i;
for(i=0; i<10; i++)
{
if(i==5)
{
printf("\n Coming out of loop when i=5 \n");
break;
}
printf("%d", i);
}
return 0;
}
Chapter – 6 : Looping
Use of Break & Continue
Output using break; statement :
01234
Coming out of loop when i= 5
Chapter – 6 : Looping
Use of Break & Continue
Continue Statement ::
In C Programs, if we want to take control to the beginning of the loop, by
passing the statements inside the loop, which have not yet been executed, in
this case we use continue.
continue is reserved keyword in C.
When continue is encountered inside any loop, control automatically passes
to the beginning of loop.
Syntax :
continue;
Chapter – 6 : Looping
Use of Break & Continue
Flowchart of continue statement
Chapter – 6 : Looping
Use of Break & Continue
Example :
int main()
{
int i;
for(i=0; i<10; i++)
{
if(i==5)
{
printf("\nSkipping %d from display using continue \n", i");
continue;
}
printf("%d", i);
}
return 0;
}
Chapter – 6 : Looping
Use of Break & Continue
Output using continue; statement :
01234
6789
Chapter – 6 : Looping
Use of if…else in loop
It is also possible that we could use if..else statement in loop as and when
required.
Example :
#include<stdio.h>
int main()
{
int i = 1; // keep looping
while (i < 100)
{
// if i is even
if(i % 2 == 0)
{
printf("%d ", i);
}
i++; // increment the number
}
return 0;
}
Chapter – 6 : Looping
Use of if…else in loop
We have declared a variable i and initialized it to 1.
Control is transferred inside the body of the while loop. Inside the body of the
loop, if condition (i % 2 == 0) is checked, if it is true then the statement inside
the if block is executed.
Then the value of i is incremented using expression i++. As there are no more
statements left to execute inside the body of the while loop, this completes the
first iteration.
Again the condition (i < 100) is checked, if it is still true then once again the
body of the loop is executed.
We can make an infinite loop by leaving its conditional expression empty. When
the conditional expression is empty, it is assumed to be true.
Example :
#include <stdio.h>
int main()
{
for(;;)
{
printf("This is not gonna end!\n");
}
return 0;
}
Chapter – 6 : Looping
Infinite loop
More Example :
Chapter – 6 : Looping
Infinite loop
Note
To terminate an infinite loop, press Ctrl + C.
Chapter – 6 : Looping
Previous year Questions
Fill in the Blanks :
1. In a do … while loop , if the body of the loop is executed n times , the test
condition is evaluated _____________ times .
3. A loop that always satisfies the test condition is known as _______________ loop.
5. When we do not know in advance the number of times the loop will be
executed , we use a ________ loop.
Chapter – 6 : Looping
Previous year Questions
State True or False :
1. In a while loop , if the body is executed n times , the test condition is
executed (n+1) times .
3. The loop control variable may be updated before or after the loop iterates.
4. The for and do. While loop are the post test loops.
5. When we place a semi colon after the for statement , the compiler will
generate an error message .
Chapter – 6 : Looping
Previous year Questions
Questions :
1. How is comma operator useful in a for loop? Explain with the help of
relevant example?
2. Give the points of similarity and difference between a while loop and
do..while loop .
4. In what situations will you prefer to use for , while and do..while loop?
Chapter – 6 : Looping