CodeBlanks Logo Icon CodeBlanks

Filling arrays

Learn to fill arrays with for.

Filling arrays

You can fill an array with a for loop. The index goes from 0 to length - 1:

int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i * 2;
}
// arr = {0, 2, 4, 6, 8}

Here each element becomes twice its index. The bound i < arr.length is safe; it never exceeds length. To print the array, use for-each.

Filling and printing

After filling the array, you can print it with for-each:

int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i * 2;
}
for (int n : arr) {
    System.out.println(n);
}

This prints 0, 2, 4, 6, 8. for-each walks the array without an index; it is ideal for printing. Filling needs an index, so the classic for is used.

Practice Fill with even numbers and print

Write a Main class with a main method. Assign new int[5] to int[] arr. With for (int i = 0; i < 5; i++) do arr[i] = i * 2. Then print all elements with for (int n : arr) { System.out.println(n); }.

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        int[] arr = new int[5];
        for (int i = 0; i < 5; i++) {
            arr[i] = i * 2;
        }
        for (int n : arr) {
            System.out.println(n);
        }
    }
}

Expected output

0
2
4
6
8

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does for (int i = 0; i < arr.length; i++) arr[i] = i; do?

  • Nothing
  • Deletes the array
  • Sorts the array
  • Fills with 0, 1, 2, ... Correct answer

Explanation: Each element gets its index: 0, 1, 2, ...

2 Complete the fill loop

Question
for (int i = 0; i < arr.length; i++) {
    arr[i] = ____;
}
Answer
for (int i = 0; i < arr.length; i++) {
    arr[i] = i;
}

Explanation: arr[i] = i writes the index value to each element.

3 Match the fill concepts

Term Meaning
for Filling
i < length Bound
arr[i] = Assignment
for-each Printing

All lessons in Beginner