Complete the code to print each element of the array.
int[] numbers = {1, 2, 3, 4, 5};
for (int [1] = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}The variable i is commonly used as the loop counter to traverse arrays in Java.
Complete the code to sum all elements in the array.
int[] values = {10, 20, 30};
int sum = 0;
for (int i = 0; i < [1]; i++) {
sum += values[i];
}
System.out.println(sum);Arrays in Java have a length property (without parentheses) to get their size.
Fix the error in the code to print all elements of the array.
String[] fruits = {"apple", "banana", "cherry"};
for (int i = 0; i <= [1]; i++) {
System.out.println(fruits[i]);
}The loop should run while i is less than fruits.length. Using i <= fruits.length - 1 is correct to avoid going out of bounds.
Fill both blanks to create a map of words to their lengths for words longer than 3 characters.
Map<String, Integer> wordLengths = new HashMap<>();
String[] words = {"cat", "elephant", "dog", "lion"};
for (String [1] : words) {
if ([2].length() > 3) {
wordLengths.put([2], [2].length());
}
}The variable word is used as the loop variable and inside the if condition to check length and add to the map.
Fill all three blanks to create a map of uppercase words to their lengths for words longer than 4 characters.
Map<String, Integer> result = new HashMap<>();
String[] words = {"tree", "mountain", "river", "sky"};
for (String [1] : words) {
if ([2].length() > 4) {
result.put([3], [2].length());
}
}The loop variable w is used to check length and to create the uppercase key for the map.
