For loop, While loop, Do while loop in c language
types of loops in C with example #For loop, While loop, Do while loop in c language #clang
Looping is a fundamental concept in C programming that allows the execution of a block of code multiple times until a specified condition is met. This process, also known as iteration, helps optimize code efficiency by reducing redundancy. In C, there are three main types of loops:
Each loop type serves different use cases, depending on whether the number of iterations is known in advance.
The for
loop is commonly used when the number of iterations is predetermined.
for (initialization; condition; update) {
// Loop body
}
#include <stdio.h>
int main() {
// Using for loop to iterate 5 times
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
The while
loop is used when the number of iterations is not known beforehand. The loop continues executing as long as the specified condition remains true.
while (condition) {
// Loop body
}
#include <stdio.h>
int main() {
int i = 1;
// Loop runs while condition is true
while (i <= 5) {
printf("Iteration %d\n", i);
i++;
}
return 0;
}
The do-while
loop is similar to the while
loop, except it guarantees that the loop body executes at least once before checking the condition.
do {
// Loop body
} while (condition);
#include <stdio.h>
int main() {
int i = 1;
// Ensures at least one execution of loop body
do {
printf("Iteration %d\n", i);
i++;
} while (i <= 5);
return 0;
}
Feature | For Loop | While Loop | Do-While Loop |
---|---|---|---|
Condition Check | Before execution | Before execution | After execution |
Use Case | When the number of iterations is known | When the number of iterations is unknown | Ensures at least one execution |
Common Usage | Iterating a known number of times | Running a loop until a condition changes | Running a loop at least once before checking |
break
statement if you need to exit a loop early based on a condition.continue
statement to skip the current iteration and move to the next.
Loops are essential in C programming for handling repetitive tasks efficiently. The for
, while
, and do-while
loops each serve different purposes, and understanding their differences allows for better control over program execution.