Loops in C are control structures that allow a set of statements to be executed repeatedly as long as a given condition is true. Instead of writing the same code multiple times, loops help reduce redundancy and make programs efficient and readable.
Loops are widely used for processing arrays, performing repetitive calculations, and controlling program flow.
The while loop is an entry-controlled loop.
The condition is checked before executing the loop body.
If the condition is false initially, the loop body will not execute even once.
while (condition)
{
// statements
}
The while loop is suitable when the number of iterations is not known in advance.
The do–while loop is an exit-controlled loop.
The loop body is executed first, and the condition is checked after execution.
Therefore, the loop executes at least once.
do
{
// statements
}
while (condition);
The semicolon at the end of the while condition is mandatory.
The for loop is used when the number of iterations is known in advance.
It combines initialization, condition checking, and increment/decrement in a single line.
for (initialization; condition; increment/decrement)
{
// statements
}
The for loop is commonly used for array traversal and counter-based repetitions.
A nested loop is a loop placed inside another loop. The inner loop executes completely for each iteration of the outer loop.
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 2; j++)
{
printf("%d %d\n", i, j);
}
}
Nested loops are commonly used in matrix operations and pattern printing programs.
The break statement is used to terminate a loop immediately
and transfer control to the statement following the loop.
if (i == 5)
break;
The continue statement skips the remaining statements of the current iteration
and moves to the next iteration of the loop.
if (i == 5)
continue;
An infinite loop is a loop that never terminates because the condition always remains true.
while (1)
{
// infinite loop
}
Infinite loops are used in embedded systems and real-time applications, but they should be handled carefully to avoid program hanging.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 5; i++)
{
printf("%d ", i);
}
return 0;
}
This program uses a for loop to print numbers from 1 to 5.
do–while loopbreak and continue