Introduction to for Loops (1)
Introduction to for Loops (1)
by Aakash
Anatomy of a For Loop
1 Initialization
Sets the initial value of the counter before entering the loop.
2 Condition
Determines how long the loop will continue running.
3 Increment/Decrement
Modifies the counter after each iteration, moving the loop
toward termination.
4 Body
The block of code executed repeatedly during each iteration.
For Loops in Python
Basic Loop Using range() Enumerate
Python's for loops iterate over The range() function generates a Use enumerate() to get both index
sequences such as lists, tuples, or sequence of numbers. and value in the loop.
strings.
Example: for i in range(5): print(i) Example: for index, value in
Example: for item in my_list: enumerate(my_list):
print(item)
For Loops in Java
Traditional For Loop Enhanced For Loop Array Iteration
Standard loop with Also known as for-each, used Useful for processing
initialization, condition, and for iterating over arrays or collections such as arrays of
increment. collections. strings efficiently.
Syntax similar to Java, controls loop Introduced in C++11 to iterate Efficient for accessing elements in
with counter variable. directly over containers. dynamic arrays (vectors).
Example: for (int i = 0; i < 10; i++) { ... } Example: for (auto& element :
my_vector) { ... }
For Loops in JavaScript
Standard For Loop For...in Loop
for (let i = 0; i < 10; i++) { ... Iterates over object
} is the classic loop. properties.
For...of Loop
Loops through iterable objects like arrays.
Use Cases
Common in tasks like matrix operations, image processing, and
grid-based games.
Conclusion
Essential Tool
For loops provide a structured way to perform repetitive tasks
efficiently in programming.