for
loop: Used when the number of iterations is known beforehand. It consists of three parts: initialization, condition, and update.
Syntax:
for(initialization; condition; update) {
// code to execute
}
Example:
for(int i = 1; i <= 5; i++) {
printf(“%d “, i);
}
Output: 1 2 3 4 5
-
while
loop: Executes as long as the specified condition is true. The condition is checked before each iteration.Syntax:
while(condition) {
// code to execute
}
Example:
int i = 1;
while(i <= 5) {
printf(“%d “, i);
i++;
}
Output: 1 2 3 4 5
-
do-while
loop: Similar to thewhile
loop, but it guarantees at least one execution of the code because the condition is checked after the loop body is executed.Syntax:
do {
// code to execute
} while(condition);
Example:
int i = 1;
do {
printf(“%d “, i);
i++;
} while(i <= 5);
Output: 1 2 3 4 5