Java Arrays Loop

Welcome to The Coding College! This tutorial focuses on using loops with Java arrays. Arrays and loops work seamlessly together to process and manipulate data efficiently. By the end of this tutorial, you’ll understand how to iterate over arrays using different types of loops.

Why Use Loops with Arrays?

When working with arrays, you often need to perform repetitive tasks, such as accessing each element, modifying values, or applying calculations. Loops make these tasks efficient and concise.

Accessing Array Elements Using Loops

Example: Accessing Elements with a for Loop

public class ArrayLoopExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};

        for (int i = 0; i < numbers.length; i++) {
            System.out.println("Element at index " + i + ": " + numbers[i]);
        }
    }
}

Output

Element at index 0: 10  
Element at index 1: 20  
Element at index 2: 30  
Element at index 3: 40  
Element at index 4: 50

Explanation: The for loop iterates through the array by using the index i.

Using a for-each Loop

The for-each loop (enhanced for loop) is a simpler way to iterate over arrays, especially when you don’t need the index.

Example

public class ForEachLoopExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry"};

        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Output

Apple  
Banana  
Cherry

Explanation: The for-each loop automatically iterates over each element in the array.

Nested Loops with Multi-Dimensional Arrays

When working with multi-dimensional arrays, nested loops are used to access elements.

Example: Iterating Over a 2D Array

public class MultiDimensionalArrayLoop {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3  
4 5 6  
7 8 9

Explanation:

  • The outer loop iterates through the rows.
  • The inner loop iterates through the columns of each row.

Modifying Array Elements Using Loops

Example: Doubling Values in an Array

public class ModifyArray {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int i = 0; i < numbers.length; i++) {
            numbers[i] *= 2; // Double each element
        }

        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output

2  
4  
6  
8  
10

Common Operations

1. Find the Sum of Array Elements

public class ArraySum {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int sum = 0;

        for (int number : numbers) {
            sum += number;
        }

        System.out.println("Sum: " + sum);
    }
}

2. Find the Largest Element

public class ArrayMax {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 5, 30, 15};
        int max = numbers[0];

        for (int number : numbers) {
            if (number > max) {
                max = number;
            }
        }

        System.out.println("Largest Number: " + max);
    }
}

3. Reverse an Array

public class ReverseArray {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int i = numbers.length - 1; i >= 0; i--) {
            System.out.print(numbers[i] + " ");
        }
    }
}

Output

5 4 3 2 1

Practice Problems

  1. Write a program to find the smallest number in an array using a loop.
  2. Create a program to count the number of even and odd elements in an array.
  3. Write a program to sort an array in ascending order using nested loops.

For more Java tutorials and coding tips, visit The Coding College. Keep exploring and refining your coding skills! 🚀

Leave a Comment