Unit 6 – C Programming Notes
(Flow of Control – Part 2)
1. Introduction to Looping
Looping is used in programming to execute a block of code repeatedly. In C, loops help
automate repetitive tasks like printing a series, calculating factorial, etc.
2. Types of Loops
a) while Loop
The while loop is an entry-controlled loop. The condition is checked before entering the
loop.
Syntax:
while(condition) {
// code
}
Example:
int i = 1;
while(i <= 5) {
printf("%d ", i);
i++;
}
b) do...while Loop
The do...while loop is an exit-controlled loop. The body executes at least once before
checking the condition.
Syntax:
do {
// code
} while(condition);
Example:
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);
c) for Loop
The for loop is used when the number of iterations is known. It has three parts:
initialization, condition, and update.
Syntax:
for(initialization; condition; update) {
// code
}
Example:
for(int i = 1; i <= 5; i++) {
printf("%d ", i);
}
3. Loop Control Statements
a) break
Used to exit from a loop prematurely.
Example:
for(int i = 1; i <= 10; i++) {
if(i == 5) break;
printf("%d ", i);
}
b) continue
Skips the rest of the loop body for the current iteration.
Example:
for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
printf("%d ", i);
}
4. Nested Loops
A loop inside another loop is called a nested loop. Useful in 2D structures like matrices or
printing patterns.
Example:
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 2; j++) {
printf("%d %d\n", i, j);
}
}
5. Infinite Loops
A loop that never ends unless a break condition is added.
Example:
for(;;) {
// infinite loop
}