Looping Through Arrays

A for loop with an index

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]);
        }
    }
}

Output

0: apple
1: banana
2: mango

Use i < fruits.length (less than), so the last i is length - 1.

The for-each loop

When you just want each value and don't need its index, the for-each loop is simpler. Read it as “for each mark in marks”:

public class Main {
    public static void main(String[] args) {
        int[] marks = {78, 92, 65, 88};
        int total = 0;
        for (int mark : marks) {
            total += mark;
        }
        System.out.println("Total: " + total);
        System.out.println("Average: " + (double) total / marks.length);
    }
}

Output

Total: 323
Average: 80.75

Finding the biggest value

Start by guessing that the first item is the biggest, then check every other item:

public class Main {
    public static void main(String[] args) {
        int[] prices = {250, 990, 120, 640};
        int max = prices[0];
        for (int price : prices) {
            if (price > max) {
                max = price;
            }
        }
        System.out.println("Most expensive: " + max);
    }
}

Output

Most expensive: 990

Filling an array from input

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = sc.nextInt();
        }
        for (int i = n - 1; i >= 0; i--) {
            System.out.print(nums[i] + " ");
        }
        System.out.println();
    }
}

Input (what the user types)

4
10 20 30 40

Output

40 30 20 10 

This common pattern reads how many numbers there are first, then the numbers themselves. Here we print them backwards.

HOME LABS COMMUNITY DASHBOARD