Looping Through Arrays

for and for-each

Example

public class Main {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Mango"};
        for (int i = 0; i < fruits.length; i++) {
            System.out.println(i + ": " + fruits[i]);
        }
        for (String f : fruits) {
            System.out.print(f.toUpperCase() + " ");
        }
        System.out.println();

        // reverse order needs the index
        for (int i = fruits.length - 1; i >= 0; i--) {
            System.out.print(fruits[i] + " ");
        }
        System.out.println();
    }
}

Output

0: Apple
1: Banana
2: Mango
APPLE BANANA MANGO 
Mango Banana Apple

Sum, Average, Max, Min

Example

public class Main {
    public static void main(String[] args) {
        int[] temps = {31, 34, 29, 36, 33, 30, 35};
        int sum = 0;
        int max = temps[0];
        int min = temps[0];
        for (int t : temps) {
            sum += t;
            if (t > max) max = t;
            if (t < min) min = t;
        }
        System.out.println("Sum: " + sum);
        System.out.printf("Average: %.2f%n", (double) sum / temps.length);
        System.out.println("Max: " + max + ", Min: " + min);
    }
}

Output

Sum: 228
Average: 32.57
Max: 36, Min: 29

Exercise: Count how many numbers in int[] nums = {4, 7, 10, 13, 16} are even.

Show answer
int evens = 0;
for (int n : nums) {
    if (n % 2 == 0) evens++;
}
System.out.println(evens);   // 3