Repetition Statements
A repetition statement is a control structure that allows a set of instructions to be executed multiple times based on a condition or a specified number of iterations.
Note- Repetition statements are also known as loops.
- The formal term for repetition is iteration.
There are three main types of repetition statements:
- For loops: Used when the number of iterations is known.
- While loops: Used when the number of iterations is unknown and depends on a condition.
- Do...while loops: Similar to while loops, but the condition is checked after the loop body is executed, ensuring the loop runs at least once.
- Use for loops when you know exactly how many times you want to repeat a block of code.
- Use while loops when the repetition depends on a condition that may change during execution.
For loops
- A for loop is a repetition statement that iterates a specific number of times, controlled by an initialisation, a condition, and an increment or decrement operation.
- Its general structure is:
for (initialization; condition; update) {
// loop body
}
- Initialisation: This only happens once, at the very start of the loop.
- Condition: Before each loop run, Java checks if the condition is true.
- If i is still less than n, the loop continues.
- If the condition is false, the loop stops.
- Loop body: The statements inside { ... } run once for every loop iteration.
- Update: After the loop body finishes, the update runs.