Standard Format for For Loops in Programming
What Is a For Loop?
A for loop repeats a block of code a specific number of times. It's one of the most used control structures in programming. If you find yourself writing the same code over and over, a for loop fixes that.
For loops are best when you know exactly how many iterations you need. If you need to loop until a condition changes, use a while loop instead.
The Basic Anatomy of a For Loop
Every for loop has three parts:
- Initialization — where you set your starting point
- Condition — when to keep going (or stop)
- Increment/Decrement — how you move toward the end
These three components sit inside parentheses, separated by semicolons. The code block that repeats goes in curly braces (or indented after a colon in Python).
For Loop Syntax Across Languages
Different languages use slightly different formats. Here's the breakdown:
Java, C, C++, C#, JavaScript
These languages share nearly identical syntax:
for (int i = 0; i < 10; i++) {
// code to repeat
}
Start at 0, keep going while i is less than 10, increase i by 1 each time. This is the classic pattern you'll see 90% of the time.
Python
Python skips the traditional three-part format. It uses a cleaner range-based approach:
for i in range(10):
# code to repeat
Python loops through each item in an iterable. The range(10) generates numbers 0 through 9 automatically.
PHP
for ($i = 0; $i < 10; $i++) {
// code to repeat
}
Same structure as C-style languages. PHP developers often prefer foreach for arrays though.
Swift
for i in 0..<10 {
// code to repeat
}
Swift uses ..< for exclusive upper bounds. The ..= variant includes the final number.
For Loop Syntax Comparison
| Language | Syntax | Notes |
|---|---|---|
| JavaScript | for (let i = 0; i < n; i++) |
Most common format |
| Python | for i in range(n) |
No curly braces, uses indentation |
| Java | for (int i = 0; i < n; i++) |
Requires declared variable type |
| C/C++ | for (int i = 0; i < n; i++) |
Same as Java |
| C# | for (int i = 0; i < n; i++) |
Identical to Java |
| PHP | for ($i = 0; $i < $n; $i++) |
Dollar sign on variables |
| Swift | for i in 0..<n |
Range operators |
| Ruby | 10.times do |i| |
Iterative methods preferred |
How To: Using For Loops in Practice
Looping Through an Array
Here's how to access every element in an array:
// JavaScript
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
# Python
fruits = ["apple", "banana", "orange"]
for i in range(len(fruits)):
print(fruits[i])
Iterating With Index and Value
Sometimes you need both the position and the value:
// JavaScript - modern approach
const items = ["a", "b", "c"];
for (const [index, value] of items.entries()) {
console.log(index, value);
}
# Python - built-in enumerate
items = ["a", "b", "c"]
for index, value in enumerate(items):
print(index, value)
Counting Down
Reverse loops use decrement instead of increment:
// JavaScript
for (let i = 10; i > 0; i--) {
console.log(i);
}
# Python
for i in range(10, 0, -1):
print(i)
Common Mistakes to Avoid
- Off-by-one errors — using
<=instead of<(or vice versa) will give you one extra or one fewer iteration than expected - Modifying the counter inside the loop — changing
iwithin the loop body causes unpredictable behavior - Infinite loops — if your increment never moves toward the exit condition, the loop runs forever
- Using floats as counters — floating-point math introduces precision errors; stick to integers
- Forgetting to initialize — using an uninitialized variable causes errors or unexpected values
For Loop vs Other Loop Types
For loops aren't always the right choice:
- While loops — use when you don't know the iteration count upfront
- For-each loops — use when you only need the values, not the indices
- Do-while loops — use when you need the code to run at least once before checking the condition
Most beginners overuse for loops. If you're looping through an entire collection and don't need the index, use a for-each or equivalent instead. It's cleaner and less error-prone.
Performance Considerations
In most languages, for loops are faster than while loops for known iteration counts. The compiler can optimize them better.
Modern languages offer functional alternatives like map, filter, and reduce. These are often slower for simple operations but produce cleaner code. For performance-critical code, stick with traditional for loops.
Cache array lengths outside the loop when iterating in languages like JavaScript:
// Slower - checks length every iteration
for (let i = 0; i < arr.length; i++)
// Faster - caches the length
for (let i = 0, len = arr.length; i < len; i++)
This matters in large loops. For small arrays, the difference is negligible.
When to Use Nested For Loops
Nested loops (a loop inside a loop) handle multi-dimensional data or grid-based operations:
// 3x3 grid
for (let row = 0; row < 3; row++) {
for (let col = 0; col < 3; col++) {
console.log(row, col);
}
}
Be careful with nested loops. Each level multiplies the total iterations. Two nested loops with 1000 iterations each means 1,000,000 total operations. This gets slow fast.