A for loop is a count-controlled loop in C++ (and many other programming languages) that repeats a block of code a specific number of times.
Why use a for loop?
When you know exactly how many times the code should repeat.
It keeps the code organized, clean, and easy to read.
Reduces errors compared to writing the same code multiple times.
Difference from while loop:
While loop is condition-controlled → may run 0 or many times.
For loop is count-controlled → usually runs a fixed number of times.
2. For Loop Syntax
Step-by-Step Explanation:
Initialization
Sets the starting value of the loop control variable (LCV).
Executed only once at the beginning.
Example:
int i = 0;→ starts counting from 0.
Condition
Checked before each iteration.
If true → loop executes.
If false → loop stops.
Example:
i < 10→ runs as long asiis less than 10.
Update
Changes the LCV after each iteration.
Usually
i++(increment by 1) ori--(decrement by 1).Can use custom updates like
i += 2.
Statements inside the loop
Executes for each iteration.
Can be one or more statements.
3. Loop Control Variable (LCV)
Definition: A variable that controls how many times the loop executes.
Usually declared in the initialization part of the for loop.
Characteristics:
Sets the starting value.
Checked against condition.
Updated in each iteration.
Proper update is necessary to avoid infinite loops.
Example:
Here,
iis the LCV.It starts at 1, runs until i <= 5, and increments by 1 each iteration.
4. Step-by-Step Execution Table
Example Code:
| Iteration | i value | Condition (i <= 5) | Action | Update i |
|---|---|---|---|---|
| 1 | 1 | True | Print 1 | i=2 |
| 2 | 2 | True | Print 2 | i=3 |
| 3 | 3 | True | Print 3 | i=4 |
| 4 | 4 | True | Print 4 | i=5 |
| 5 | 5 | True | Print 5 | i=6 |
| 6 | 6 | False | Stop | – |
Observation: Loop executes 5 times, exactly as controlled by the LCV.
5. Variations of For Loop
a) Incrementing Loop
Starts at 0, increments by 1 each time.
Prints
0 1 2 3 4 5 6 7 8 9.
b) Decrementing Loop
Starts at 5, decrements by 1 each time.
Prints
5 4 3 2 1.
c) Custom Update
Increments by 2 each iteration.
Prints
0 2 4 6 8 10.
d) Multiple Loop Control Variables
Prints
(0,10) (1,9) (2,8) (3,7) (4,6) (5,5)Shows two LCVs updating together.
6. Nested For Loops
A for loop inside another for loop is called a nested for loop.
Useful for patterns, tables, and 2D structures.
Example: Multiplication Table
Output:
Explanation:
Outer loop controls rows (
i).Inner loop controls columns (
j).LCVs are independent.
7. Common Mistakes
Infinite loop
Loop never executes
Wrong type for LCV
8. Practical Applications
Printing numbers 1 to 100
Summation of numbers
Prints
55→ sum of numbers 1 to 10
Array iteration
Prints
10 20 30 40
Patterns
Output: