What is a for Loop?
A for loop is a looping statement used to repeat a block of code a fixed number of times.
Use a for loop when:
- You know in advance how many times the loop should run.
Syntax of for Loop
for(initialization; condition; increment/decrement) {
// statements
}Parts of for Loop (Very Important)
1. Initialization
- Runs only once
- Declares & initializes loop variable
int i = 1;2. Condition
- Checked before every iteration
- Loop runs while condition is true
i <= 53. Increment / Decrement
- Changes loop variable value
- Prevents infinite loop
i++; // increment
i--; // decrementSimple Example: Print 1 to 5
c
1#include <stdio.h>
2
3int main() {
4 int i;
5
6 for(i = 1; i <= 5; i++) {
7 printf("%d\n", i);
8 }
9
10 return 0;
11}Output:
1
2
3
4
5Some Examples
1. Print Even Numbers
for(int i = 2; i <= 10; i += 2) {
printf("%d ", i);
}Output:
2 4 6 8 102. Reverse Loop (Decrement)
for(int i = 5; i >= 1; i--) {
printf("%d ", i);
}Output:
5 4 3 2 1for Loop Variations
1. Multiple initialization & increment
for(int i = 1, j = 5; i <= j; i++, j--) {
printf("%d %d\n", i, j);
}2. Empty loop body
for(int i = 0; i < 5; i++);⚠️ Semicolon means no body (common mistake)
3. Infinite for Loop
for(;;) {
printf("Echo is looping");
}Reason:
- No condition → always true
