In programming, loops are used to repeat a set of instructions multiple times, making them essential for efficient coding. Loops help to:
- Automate repetitive tasks – e.g., counting from 1 to 100.
- Reduce redundancy – no need to copy-paste code.
- Handle large amounts of data efficiently – e.g., processing arrays or lists.
In Java, there are four main types of loops:
- For loop
- Enhanced for loop (For-each loop)
- While loop
- Do-while loop
For Loop
The for loop is ideal when you know exactly how many times you want to repeat a task. It’s great for counting or iterating through a set number of iterations.
Syntax:
for (initialisation; condition; update) {
// code to repeat
}
Explanation of parts:
- Initialisation: Sets a starting value for the loop counter.
- Condition: The loop keeps running while this condition is true.
- Update: Updates the counter after each iteration (increment/decrement).
Example:
int count = 5;
for (int index = 0; index < count; index++) {
System.out.println(index);
}
Output:
0
1
2
3
4
Breakdown:
- The loop starts with
index = 0. - Each iteration prints the current value of
index. - After printing,
indexincreases by 1. - When
indexreaches 5, the loop terminates. Last number printed is 4
When to use: For tasks that require a specific number of repetitions, like iterating through a fixed range.
Enhanced For Loop (For-each Loop)
The enhanced for loop is a more concise and readable way to iterate over arrays or collections when you don’t need to access the index of elements.
Syntax:
for (datatype item : array) {
// code using item
}
Example
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Output:
1
2
3
4
5
Key Points:
- You directly access each value (
number) in the array instead of using an index. - Limitations:
- Cannot skip elements.
- Cannot loop backwards.
- Cannot access the index of the element.
When to use: For simple array or collection processing where you only need to use the element itself.
While Loop
The while loop is useful when you don’t know in advance how many times you need to repeat an action. The loop continues as long as the specified condition remains true.
Syntax:
while (condition) {
// code to repeat
}
Example
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("exit")) {
System.out.println("Enter text 'exit' to quit: ");
input = scanner.nextLine();
}
scanner.close();
Explanation:
- The loop keeps prompting the user for input until they enter “exit”.
- The condition checks if the user input is not equal to “exit”. If it’s true, the loop continues.
When to use: When you don’t know how many iterations are needed upfront, but the loop will end when a condition is met.
Do-While Loop
The do-while loop is similar to the while loop, but the key difference is that it guarantees at least one iteration, because the condition is checked after the loop executes.
Syntax:
do {
// code to repeat
} while (condition);
Example
import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
String correctPassword = "password";
String input = "";
do {
System.out.println("Enter password: ");
input = scanner.nextLine();
} while (!input.equals(correctPassword));
scanner.close();
Explanation:
- The user is prompted at least once to enter the password.
- The loop continues prompting until the user enters the correct password.
When to use: When you want to ensure that the loop runs at least once, regardless of the condition.
Break and Continue Statements
The break statement
The break statement is used to exit a loop early, even if the loop’s condition hasn’t yet become false. This can be useful when you need to stop the loop based on a condition that arises during iteration.
Example (Using break to exit a loop early):
for (int i = 0; i < 10; i++) {
if (i == 5) {
System.out.println("Exiting loop early when i is 5.");
break; // Exits the loop when i is 5
}
System.out.println("i: " + i);
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
Exiting loop early when i is 5.
Explanation:
- The
forloop starts fromi = 0and continues untili = 9. - When
i == 5, thebreakstatement is executed, which causes the loop to exit early.
The continue statement
The continue statement is used to skip the current iteration of the loop and move to the next iteration. It does not terminate the loop; instead, it just skips the rest of the code inside the loop for the current iteration.
Example (Using continue to skip even numbers):
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skips the current iteration for even numbers
}
System.out.println("Odd number: " + i);
}
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Odd number: 7
Odd number: 9
Explanation:
- The loop iterates from
i = 0toi = 9. - If
iis an even number (i % 2 == 0), thecontinuestatement is executed, which skips the print statement and moves to the next iteration. - As a result, only the odd numbers are printed.
Infinite Loop
An infinite loop occurs when the loop’s condition is always true and never becomes false, causing the loop to run indefinitely. This is generally not recommended, but you can intentionally create infinite loops in some situations (e.g., server processes or long-running programmes).
Example (Infinite while loop):
while (true) {
System.out.println("This loop will run forever.");
}
Output:
This loop will run forever.
This loop will run forever.
This loop will run forever.
...
Explanation:
- The condition
trueis always true, so thewhileloop will never stop running. - Warning: Infinite loops can cause your programme to hang or consume excessive resources, so they must be used carefully. Always ensure there’s a way to break out of an infinite loop when needed (like using
breakor some condition).
Summary
- For loop: Use when you know the number of repetitions in advance (e.g., counting from 1 to 100).
- Enhanced for loop: Use for iterating through arrays or collections where you don’t need the index.
- While loop: Use when the number of repetitions is unknown and depends on a condition.
- Do-while loop: Similar to the
whileloop, but guarantees at least one iteration. - Break and Continue: You can use
breakto exit a loop early orcontinueto skip to the next iteration. - Infinite loops: Be careful! If your condition never becomes false, your loop will run indefinitely. Always ensure there’s a way for the condition to eventually fail.
Leave a Reply