π C For Loop – Count & Repeat with Style
The for loop in C is your go-to loop when you know exactly how many times you want to repeat a block of code. Itβs like setting a timer: start here, stop there, and count up!
πΉ Syntax of for loop
for (initialization; condition; increment) { // code to execute }
π Example: Print 1 to 5
This program prints numbers from 1 to 5 using a for
loop.
#include <stdio.h> int main() { for (int i = 1; i <= 5; i++) { printf("Number: %d\n", i); } return 0; }
π Example: Print Even Numbers
This version prints even numbers from 2 to 10.
#include <stdio.h> int main() { for (int i = 2; i <= 10; i += 2) { printf("Even: %d\n", i); } return 0; }
π― Key Points
- The
for
loop is compact and efficient for counting tasks. - All three parts (init, condition, increment) are in one line.
- You can also loop backward or skip numbers (e.g., i -= 1 or i += 3).
π Practice Time!
Try printing odd numbers, countdowns, or even create your own mini table generator using the for
loop!