A loop is a programming construct that allows you to repeat a block of code multiple times.
Instead of writing the same code repeatedly, loops help automate repetitive tasks efficiently.
There are 3 main types of loops in C:
for loopThe for loop is used when the number of iterations is known beforehand.
for (initialization; condition; update) {
// Code to execute repeatedly
}
Example: Print numbers from 1 to 5
for (int i = 1; i <= 5; i++) {
printf("%d\n", i);
}
while loopThe while loop executes as long as the condition is true.
while (condition) {
// Code to execute repeatedly
}
Example: Print numbers from 1 to 5
int i = 1;
while (i <= 5) {
printf("%d\n", i);
i++;
}
do-while loopThe do-while loop executes the code block at least once, then repeats as long as the condition is true.
do {
// Code to execute
} while (condition);
Example: Print numbers from 1 to 5
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 5);
| Loop Type | Execution | Condition Check | When to Use |
|---|---|---|---|
for |
Known number of iterations | Before each iteration | When iteration count is known |
while |
Unknown iterations | Before each iteration | Repeat while condition is true |
do-while |
At least once | After each iteration | When code must run at least once |
for loop to print the multiplication table of 7 (from 7×1 to 7×10).while loop to calculate the sum of numbers from 1 to 50.do-while loop to repeatedly ask the user to enter a number until they enter 0.For more detailed information, examples, and explanation on loops in C, visit the Programiz - C Loops Tutorial.