1
C PROGRAMMING LECTURE
THE LOOP CONTROL STRUCTURE
@ AMITY UNIVERSITY, Gwalior
The LOOP Control Structure
2
This involves repeating some portion of the program either a specified number of times or until a particular condition is being satisfied.
There are three methods by way of which we can repeat a part of a program. They are:
Using a for statement
Using a while statement Using a do-while statement
The for Loop
3
The operation of the for loop is illustrated as:
START initialize
test TRUE Body of loop increment
FALSE
STOP
Contd
4 4
General form of for :
for(initialize counter; test counter; increment counter) { do this; and this; and this; }
Examples
5
void main() { int i; for(i=1;i<=10;) { printf(%d\n,i); printf(%d\n,i); i=i+1; } }
(a)
(b) void main() { int i=1; for(;i<=10;) {
i=i+1; } }
The while Loop
6
The operation of the while loop is illustrated as: START
initialize
test TRUE Body of loop increment
FALSE
STOP
Contd
7
General form of while:
initialize loop counter; while (test loop counter using a condition) { do this; and this; increment loop counter; }
Examples
8
void main() { int i=1; while(i<=10) { printf(%d\n, i); i=i+1; } }
The do-while Loop
9
The operation of the do-while loop is illustrated as: START
initialize Body of loop increment
TRUE test FALSE STOP
Contd
10 10
General form of do-while:
do {
this; and this; and this;
} while(this condition is true);
Find Outputs ..
11
void main() { int i=1; while(i<=10) { printf(%d\n,i); i++; }
void main() { int i; for(i=1;i<=5;) { printf(%d\n,i); i++; } }
End of Todays Lecture
12