for Loop in C
The for loop repeats a block of code a fixed number of times. It is the most used loop when you know in advance how many iterations are needed.
Syntax — 3 Parts
c
for (initialization; condition; update) {
// body — runs while condition is true
}| Part | Runs When | Example |
|---|---|---|
| Initialization | Once at start | int i = 1 |
| Condition | Before EVERY iteration | i <= 10 |
| Body | While condition is true | printf("%d", i) |
| Update | After EVERY iteration | i++ |
Complete for Loop Examples
c
#include <stdio.h>
int main() {
int i;
// Count 1 to 10
printf("Count up : ");
for (i = 1; i <= 10; i++) printf("%d ", i);
printf("\n");
// Count down
printf("Count down: ");
for (i = 10; i >= 1; i--) printf("%d ", i);
printf("\n");
// Sum of 1 to 100
int sum = 0;
for (i = 1; i <= 100; i++) sum += i;
printf("Sum 1 to 100 = %d\n", sum);
// Multiplication table of 7
printf("\nTable of 7:\n");
for (i = 1; i <= 10; i++)
printf("7 x %2d = %3d\n", i, 7*i);
return 0;
}▶ Output
Count up : 1 2 3 4 5 6 7 8 9 10 Count down: 10 9 8 7 6 5 4 3 2 1 Sum 1 to 100 = 5050 Table of 7: 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Nested for Loop — Star Triangle Pattern
c
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++)
printf("* ");
printf("\n");
}▶ Output
* * * * * * * * * * * * * * *