for Loops
Introduction to For Loops
- A for loop is a control flow statement, allowing code to be executed repeatedly.
- These loops are typically used when the number of iterations is known beforehand.
- The basic structure of a for loop includes initialisation, test condition, and increment/decrement.
For Loop Syntax
- In a for loop, the initialisation usually involves setting a control variable to a start value.
- The test condition checks if the loop should continue.
- Increment/decrement changes the control variable’s value after each loop cycle. Commonly, this means increasing or decreasing by 1.
Using For Loops
- Control variables can be used within the loop to perform calculations or manipulate other variables.
- Braces ({ and }) encapsulate what runs each iteration of the loop. If only one line follows the for statement, braces can be omitted.
- It’s important to ensure the loop will end, preventing an infinite loop. This typically means designing the test condition and increment/decrement correctly.
Developing Algorithms with For Loops
- Algorithms often require repeated actions, making for loops particularly useful.
- Nested for loops allow for the execution of other loops within a single iteration of the main loop, often used for multi-dimensional arrays or complex counting tasks.
- The break statement can be used to prematurely terminate the loop, usually based on a certain condition being met.
- The continue statement can be used to skip one iteration of the loop, moving onto the next iteration.
Advanced For Loop Concepts
- A for-each loop (also known as an enhanced for loop) is used to traverse items in collections (like arrays or lists). It’s more concise but less flexible than a traditional for loop.
- For loops can also iterate over characters in a string, or elements in a data structure.
- Iterating over data structures or strings is fundamental to many algorithms, from sorting and searching, to data analysis and transformation.