Loops in C: for, while, do-while
1. FOR Loop
- Best when you know how many times to loop.
- Syntax:
for(initialization; condition; increment) {
// code
Example:
#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
printf("%d ", i);
return 0;
Output: 1 2 3 4 5
---------------------------------------------
2. WHILE Loop
- Used when number of iterations is unknown.
- Condition is checked before loop body.
Syntax:
while(condition) {
// code
Example:
#include <stdio.h>
int main() {
int i = 1;
while(i <= 5) {
printf("%d ", i);
i++;
return 0;
Output: 1 2 3 4 5
---------------------------------------------
3. DO-WHILE Loop
- Always executes at least once.
- Condition checked after loop body.
Syntax:
do {
// code
} while(condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d ", i);
i++;
} while(i <= 5);
return 0;
Output: 1 2 3 4 5