
For Loop in C
The for
loop in C is a control structure used to repeat a block of code a specific number of times. It’s ideal when you know how many times you want to loop. ??
? Basic Syntax
#include <stdio.h>int main() { for (int i = 1; i <= 5; i++) { printf("i = %d\n", i); } return 0;}
Output:
i = 1i = 2i = 3i = 4i = 5
? Breakdown of Components
Part | Description |
---|---|
Initialization | Happens once at the start (int i=0 ) |
Condition | Checked before each loop (i <= 5 ) |
Increment | Runs after each loop (i++ ) |
? Decrementing Example
for (int i = 5; i >= 1; i--) { printf("%d ", i);}
Output: 5 4 3 2 1
?? Infinite Loop
If you omit the condition:
for (;;) { // runs forever unless you break}
? Nested For Loop
for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 2; j++) { printf("i=%d, j=%d\n", i, j); }}
? Useful With Arrays
int nums[] = {10, 20, 30};int size = sizeof(nums) / sizeof(nums[0]);for (int i = 0; i < size; i++) { printf("%d ", nums[i]);}