Loops, also known as iterative statements, are used in C to execute a block of code repeatedly as long as a specified condition remains true. They are fundamental for automating repetitive tasks.
C Programming: Loops / Iterative Statements 🔁
Loops allow you to
write compact code that avoids redundancy. C provides three types of loops: for
, while
, and do-while
. These are categorized into two main types:
·
Entry-controlled
loops: The condition is checked before
executing the loop body. The body may not execute at all if the condition is
initially false. (for
and while
)
·
Exit-controlled
loops: The condition is checked after
executing the loop body. The body is guaranteed to execute at least once. (do-while
)
1. The while
Loop
A while
loop is an entry-controlled loop that is ideal when
the number of iterations is not known in advance. The loop continues as
long as the condition is true.
· Syntax:
C
while (condition) {
// statements to execute
}
Example
This program reads
numbers from the user and calculates their sum, stopping only when the user
enters 0
.
C
#include <stdio.h>
int main() {
int number;
int sum =
0;
printf(
"Enter a number (enter 0 to stop): ");
scanf(
"%d", &number);
while (number !=
0) {
sum += number;
// Add the number to the sum
printf(
"Enter a number (enter 0 to stop): ");
scanf(
"%d", &number);
}
printf(
"The sum of the entered numbers is: %d\n", sum);
return
0;
}
2. The for
Loop
A for
loop is an entry-controlled loop that is perfect for
when you know the number of iterations in advance. It combines
initialization, condition checking, and modification into a single, compact
line.
· Syntax:
C
for (initialization; condition; modification) {
// statements to execute
}
Example
This program prints the multiplication table for the number 5.
C
#include <stdio.h>
int main() {
int number =
5;
int i;
printf(
"Multiplication Table for %d:\n", number);
// Loop from 1 to 10
for (i =
1; i <=
10; i++) {
printf(
"%d x %d = %d\n", number, i, number * i);
}
return
0;
}
size=2 width="100%" align=center>
3. The do-while
Loop
A do-while
loop is an exit-controlled loop. Its key feature is
that the loop body is guaranteed to execute at least once because the
condition is checked at the end of the iteration.
· Syntax:
C
do {
// statements to execute
}
while (condition);

Example
This program displays a menu and asks for a choice. It will keep displaying the menu until the user enters a valid choice (1, 2, or 3).
C
#include <stdio.h>
int main() {
int choice;
do {
// This menu is always displayed at least once
printf(
"\n--- MENU ---\n");
printf(
"1. Start Game\n");
printf(
"2. Load Game\n");
printf(
"3. Quit\n");
printf(
"Enter your choice: ");
scanf(
"%d", &choice);
}
while (choice <
1 || choice >
3);
// Repeat if choice is not 1, 2, or 3
printf(
"You selected option %d.\n", choice);
return
0;
}