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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
Challenge
EasyWrite 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
}
}