Menu
Coddy logo textTech

Loop Through

Lesson 12 of 16 in Coddy's Strings and Arrays in Java course.

You can loop through the array elements with the for loop and use the length property to specify how many times the loop should run.

double[] coolNums = {3.14, 1.69, 9.99};
for (int i = 0; i < coolNums.length; i++) {
	System.out.println(coolNums[i]);
}

The above prints all the numbers in the array!

There is also a shorter form for an array called a "for-each" loop:

double[] coolNums = {3.14, 1.69, 9.99};
for (int num : coolNums) {
	System.out.println(num);
}

The full format is:

for (type variableName : arrayName) {
	// loop body
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

Write a function named onlyOdd that gets an array of integers as an argument and prints only the odd numbers.

Try it yourself

class OnlyOdd {
    public static void onlyOdd(int[] nums) {
        // Write code here
    }
}

All lessons in Strings and Arrays in Java