For loop
What Is Iteration?
Iteration means repeating a set of instructions multiple times. In Java, loops allow us to automate repetitive tasks instead of writing many segments of similar code over and over.
Types of Loops in Java:
- for loop - use when you know how many times to repeat
- enhanced for loop (for-each) - great for looping through arrays/lists
- while loop - repeats while a condition is true (covered separately)
- do-while loop - runs at least once (covered separately)
The for loop
The syntax for a for loop is as follows:
- Initialization: runs once at the start (e.g., int i = 0)
- Condition: checked before each repetition; loop continues while true
- Update: runs after each iteration
Examples of updates:
++increases i by 1--decreases i by 1- Custom increment:
i = i + 3
We can use a for loop to count from 1 to 5:
Traversing an array using a for loop:
Enhanced for Loop (for-each)
This is a simplified version of the for loop used to iterate over arrays. It is appreciated for its simpler and more elegant syntax.
- Variable: The iterative variable corresponding to a value of an element in the array
- Collection: The array of elements being iterated over
Note: In for-each loops, the variable corresponds to a value, not an index.
Example of a for-each loop:
The loop automatically:
- Starts at the beginning
- Grabs each element in the array
- Assigns it to the variable
- Repeats until the end of the array
Use for-each loops when:
- You don't need the index
- You just want to access each item
While Loop
Unlike for loops, which are best when you know how many times to repeat, while and do-while loops are useful when the number of repetitions is unknown.
What happens in the loop:
- Checks the condition first
- Only enters the loop if the condition is true
- If the condition is false at the start, the loop does not run at all
Example of input validation using a while loop:
do-while Loop
What it does:
- Runs the loop body once, then checks the condition
- If the condition is true, it repeats
- Always executes at least one time
Example of a simple menu system with a do-while loop: