C For Loop

C for Loop (Complete Tutorial: Beginner → Advanced)
The for loop in C language is used when you know in advance how many times a block of code should execute.
It is one of the most commonly used loops in C, especially in DSA, arrays, and interviews.
What is a for Loop?
A
forloop repeatedly executes a block of code until a given condition becomes false.
Syntax of for Loop
Execution Order
Initialization (once)
Condition check
Loop body
Increment / Decrement
Repeat from step 2
Simple for Loop Example
Output:
for Loop with Decrement
Output:
Infinite for Loop
- Runs forever
- Must use
breakto stop
for Loop with Multiple Variables
- Useful in advanced logic
for Loop with Arrays
- Very common in DSA
Nested for Loop (Pattern Programs)
Output:
break and continue in for Loop
break – Exit Loop
Output: 1 2
continue – Skip Iteration
Output: 1 2 4 5
for Loop Without Body
- Semicolon makes loop body empty
Output:5
for Loop vs while Loop
| Feature | for | while |
|---|---|---|
| Best for | Fixed iterations | Unknown iterations |
| Initialization | Inside loop | Outside loop |
| Readability | High | Medium |
Common Mistakes
- Using
=instead of==in condition - Infinite loop due to wrong condition
- Forgetting increment/decrement
- Extra semicolon after
for
Interview Questions (Must Prepare)
Difference between
forandwhileCan
forloop run without initialization?What is
for(;;)?Can we use multiple variables in
forloop?Difference between
breakandcontinue
Real-Life Use Cases
Pattern printing
Searching & sorting
Embedded loops
Competitive programming
Summary
forloop is ideal for known iterations- Supports initialization, condition & update
- Can be nested and infinite
- Essential for DSA & interviews
