Introduction to For Loop
The for
loop is one of the most commonly used looping structures in Java. It allows you to repeatedly execute a block of code a specific number of times. The for
loop is particularly useful when you know beforehand how many times a task needs to be repeated. It is concise, flexible, and makes iterative programming easy to read and maintain
Syntax of For Loop
for (initialization; condition; update) {
// Code to execute in each iteration
}
- Initialization: This is executed once at the start of the loop. It is used to initialize the loop control variable(s).
- Condition: This is evaluated before each iteration. If the condition is true, the loop body executes. If false, the loop terminates.
- Update: This is executed after each iteration to update the loop control variable(s).
Key Points About For Loop
- Deterministic Loop:
- The
for
loop is ideal when you know the exact number of iterations.
- The
- Compact Syntax:
- The initialization, condition and update statements are all written in a single line, making the loop compact and readable.
- Avoids Infinite Loops:
- With proper initialization, condition and update, the
for
loop minimizes the chances of infinite looping.
- With proper initialization, condition and update, the
- Flowchart of For Loop
- Execute the initialization statement.
- Check the condition.
- If the condition is true, execute the loop body.
- Update the loop variable(s).
- Repeat steps 2–4 until the condition evaluates to false.
Examples of For Loop
Example 1: Print Numbers from 1 to 5
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 2: Sum of First 10 Natural Numbers
public class SumExample {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i; // Add i to sum
}
System.out.println("Sum of first 10 natural numbers: " + sum);
}
}
Output:
Sum of first 10 natural numbers: 55
Example 3: Printing an Array Using For Loop
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 2
Element at index 1: 4
Element at index 2: 6
Element at index 3: 8
Element at index 4: 10
Example 4: Nested For Loop
public class NestedForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Output:
i: 1, j: 1
i: 1, j: 2
i: 1, j: 3
i: 2, j: 1
i: 2, j: 2
i: 2, j: 3
i: 3, j: 1
i: 3, j: 2
i: 3, j: 3
Enhanced For Loop (For-Each Loop)
Java also provides an enhanced for loop, known as the for-each loop, which is specifically designed for iterating over collections and arrays.
Syntax of For-Each Loop
for (type variable : array) {
// Code to execute for each element
}
Example: Iterating Over an Array
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println("Number: " + num);
}
}
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Common Mistakes and How to Avoid Them
- Infinite Loops:
- Always ensure the condition will eventually evaluate to false.
- Off-by-One Errors:
- Carefully plan the starting and ending points of your loop to avoid iterating one extra or one fewer time.
- Incorrect Updates:
- Ensure that the loop variable is updated appropriately within the loop to avoid logical errors.
Advantages of For Loop
- Compact and Readable:
- Combines initialization, condition, and update in one line.
- Control Over Iterations:
- Provides precise control over the number of iterations.
- Flexibility:
- Can be used for a variety of tasks, including simple iterations, complex calculations and nested operations.