Java For & Foreach Loop

For Loop in Java

In Java, a for loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. It’s typically used when you know how many times you want to repeat a block of code.
Basic structure:

for (initialization; condition; increment/decrement) {
    // Code block to execute in the for loop
}

For Loop Example:

Loop 1 (i = 1):
The code initializes a variable i to 1 (i = 1). The condition is checked to see if i <= 4. Since i = 1 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 1”. Now i will be increased by 1, so i will become 2.
Loop 2 (i = 2):
i is now 2, and the condition is checked again. Since i = 2 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 2”. Now i will be increased by 1, so i will become 3.
Loop 3 (i = 3):
i is now 3, and the condition is checked again. Since i = 3 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 3”. Now i will be increased by 1, so i will become 4.
Loop 4 (i = 4):
i is now 4, and the condition is checked again. Since i = 4 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 4”.
Loop 5 (i = 5):
i is now 5, and the condition is checked again. Since i = 5 is not less than or equal to 4, the loop will end.

For Loop Statement

Scenario: Sum all numbers from 1 to 5, i.e., 1 + 2 + 3 + 4 + 5 = 15 using a for loop.

public class SumOfNumbers {
    public static void main(String[] args) {
        int sum = 0;
        for (int j = 1; j <= 5; j++) {
            sum += j;
        }
        System.out.println(“Sum of numbers from 1 to 5: ” + sum);
    }
}

Output: Sum of numbers from 1 to 5: 15

Code Explanation

public class SumOfNumbers

This defines a new class named SumOfNumbers.

public static void main(String[] args)

This is the entry point of the program.

int sum = 0;

It declares a variable named sum of type int and assigns it the value 0.

for (int j = 1; j <= 5; j++)

This is a for loop that runs from j = 1 to j = 5. The loop has three parts:
    ● Initialization: Assigns the value 1 to the variable j (int j = 1).
    ● Checking the condition: j is checked to see if it is less than or equal to 5 (j <= 5).
    ● Increment/Decrement (j++): In each iteration, j is increased by 1 using j++. For each iteration of the loop, the code inside the {
       } block will be executed.

sum += j;

The above code sum += j adds the current value of j to the sum variable.
    ● 1st iteration: sum += j (sum = 0, j = 1, so 0 + 1 = 1 will be saved in the sum variable).
    ● 2nd iteration: sum += j (sum = 1, j = 2, so 1 + 2 = 3 will be saved in the sum variable).
    ● 3rd iteration: sum += j (sum = 3, j = 3, so 3 + 3 = 6 will be saved in the sum variable).
    ● 4th iteration: sum += j (sum = 6, j = 4, so 6 + 4 = 10 will be saved in the sum variable).
    ● 5th iteration: sum += j (sum = 10, j = 5, so 10 + 5 = 15 will be saved in the sum variable).
    ● 6th iteration: The loop will check the condition j <= 5, but since j = 6, the condition fails, and the loop ends.

System.out.println(“Sum of numbers from 1 to 5: ” + sum);

After the loop ends, this line prints the sum of numbers from 1 to 5 to the console.

Output: Sum of numbers from 1 to 5: 15

Foreach Loop in Java

In Java, the foreach loop is used to iterate over elements in a collection, array, or other iterable objects. It simplifies the process of iterating through each element without needing to keep track of indices or the length of the collection manually.
Basic structure:

for (type item : collection) // `item` is a local variable
{
    // Statements to be executed for each `item` in the collection, e.g., collection is {14, 8, 21, 5, 37, 2}}

The loop starts, and for the first iteration, it assigns the first element of the collection array to the local variable item. The code inside the loop body is executed using the value of the first element (item) from the array. After completing the code execution for the first element, the loop moves to the next element in the array. This process continues until all elements in the array have been processed. The loop automatically handles the iteration and termination. After processing all elements in the array, the loop terminates.

Foreach Loop Statement

Scenario: Write a Java program using a foreach loop that finds the maximum value from an array of integers and prints it to the console.

public class FindMaxNumber {
    public static void main(String[] args) {
        int[] collectionOfNumbers = { 14, 8, 21, 5, 37, 2 };
        int max = collectionOfNumbers[0];
        for (int number : collectionOfNumbers) {
            if (number > max) {
                max = number;
            }
        }
        System.out.println(“The maximum value in the array is: ” + max);
    }
}

Output: The maximum value in the array is: 37

Code Explanation

public class FindMaxNumber

This defines a new class named FindMaxNumber.

public static void main(String[] args)

This is the entry point of the program.

int[] collectionOfNumbers = { 14, 8, 21, 5, 37, 2 };

It declares a variable named collectionOfNumbers of type int array and assigns it six integer values – {14, 8, 21, 5, 37, 2}.

int max = collectionOfNumbers[0];

It declares an integer variable max and assigns it the value of the first element in the collectionOfNumbers array. Initially, max is set to 14, the number at index 0.

for (int number : collectionOfNumbers)

This is a foreach loop that iterates over each element in the collectionOfNumbers array. It assigns each element to the variable number one at a time.
    ● 1st iteration: The value of max is 14, and number is 14. Since number is not greater than max, the if block is skipped, and
        the iteration continues.
    ● 2nd iteration: The value of max remains 14, and number is 8. Since number is not greater than max, the if block is skipped,
       and the iteration continues.
    ● 3rd iteration: The value of max remains 14, and number is 21. Since number is greater than max, the if block is executed,
       and max is updated to 21.
    ● 4th iteration: The value of max is now 21, and number is 5. Since number is not greater than max, the if block is skipped,
       and the iteration continues.
    ● 5th iteration: The value of max remains 21, and number is 37. Since number is greater than max, the if block is executed,
       and max is updated to 37.
    ● 6th iteration: The value of max is now 37, and number is 2. Since number is not greater than max, the if block is skipped,
       and the iteration ends.

if (number > max)

This line checks if the current element (number) is greater than the current maximum value (max). If it is, the code inside the if block is executed.

max = number;

This line assigns the value of number to the variable max if number is greater than max.

System.out.println(“The maximum value in the array is: ” + max);

This line prints the maximum value found in the array to the console.

Output: The maximum value in the array is: 37

Tasks:
1. You need to create a program that prints the multiplication table of a given number using a for loop. The program should display the multiplication table from 1 to 10 for the specified number. First you have to take input from console
Output:

2. Print Even Numbers: Use a for loop to iterate from 1 to 20. Inside the loop, use an if-else statement to print only even numbers.
3. Sum of Multiples of 3: Use a for loop to iterate from 1 to 30. Inside the loop, use an if-else statement to check if the number is a multiple of 3. Sum the multiples of 3 and print the result at the end.
4. Weekday/Weekend Checker: Use a for loop to iterate through an array of days of the week (“Monday”, “Tuesday”, etc.). Inside the loop, use a switch statement to print “Weekday” for Monday to Friday and “Weekend” for Saturday and Sunday.
5. Grade Classifier: Use a for loop to iterate through an array of grades (‘A’, ‘B’, ‘C’, ‘D’, ‘F’). Inside the loop, use a switch statement to print the description of each grade. Inside each switch case, use an if-else statement to print a motivational message for grades A and B.
6. Month Days Printer: Use a for loop to iterate through an array of month numbers (1 to 12). Inside the loop, use a switch statement to print the number of days in each month. Use an if-else statement inside the switch case for February to check for leap years.
7. Identify Prime Numbers: Use a for loop to iterate from 1 to 50. Inside the loop, use an if-else statement to check if the number is prime. Print the prime numbers.
8. Basic Iteration: Write a Java program that uses an enhanced for loop (for-each) to iterate over an array of integers and print each value to the console.
9. Summing Elements: Given a list of integers, use an enhanced for loop (for-each) to calculate and print the sum of all the elements.
10. Finding Maximum Value: Write a Java program that uses an enhanced for loop (for-each) to find and print the maximum value in an array of integers.
11. Counting Elements: Use an enhanced for loop (for-each) to count how many elements in a list of integers are greater than a specified value.
12. String Lengths: Given a list of strings, use an enhanced for loop (for-each) to print each string and its length.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

A for loop is used to execute a block of code repeatedly based on a specified condition.

A foreach loop simplifies iteration over arrays and collections without using an index.

for (initialization; condition; update) { // code block }

for (Type item : collection) { // code block }

A for loop requires manual control of iteration, while a foreach loop automatically iterates over elements.

Yes, foreach loops work seamlessly with arrays and collections in Java.

Yes, exercises like iterating through arrays and calculating sums are included.

Yes, the tutorial is free and available online.

It is designed for beginners learning Java programming.

Examples include iterating arrays, printing elements, and calculating totals.