Challenge - 5 Problems
Array Traversal Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of nested array traversal
What is the output of the following Java code that traverses a 2D array?
Java
public class Main { public static void main(String[] args) { int[][] matrix = {{1, 2}, {3, 4}}; int sum = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { sum += matrix[i][j]; } } System.out.println(sum); } }
Attempts:
2 left
💡 Hint
Think about adding all elements in the 2D array.
✗ Incorrect
The code sums all elements: 1 + 2 + 3 + 4 = 10.
❓ Predict Output
intermediateOutput of enhanced for-loop traversal
What will be printed by this Java code that uses an enhanced for-loop to traverse an array?
Java
public class Main { public static void main(String[] args) { String[] fruits = {"apple", "banana", "cherry"}; for (String fruit : fruits) { System.out.print(fruit.charAt(0)); } } }
Attempts:
2 left
💡 Hint
Look at the first character of each string.
✗ Incorrect
The code prints the first character of each fruit: 'a', 'b', 'c'.
🧠 Conceptual
advancedUnderstanding array traversal with break statement
What is the output of this Java code that traverses an array and uses a break statement?
Java
public class Main { public static void main(String[] args) { int[] numbers = {5, 10, 15, 20}; int total = 0; for (int num : numbers) { if (num == 15) { break; } total += num; } System.out.println(total); } }
Attempts:
2 left
💡 Hint
The loop stops when it reaches 15.
✗ Incorrect
The loop adds 5 and 10, then breaks before adding 15, so total is 15.
🔧 Debug
advancedIdentify the error in array traversal
What error will this Java code produce when run?
Java
public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Attempts:
2 left
💡 Hint
Check the loop condition and array indices.
✗ Incorrect
The loop tries to access arr[3], which is out of bounds (max index 2).
🚀 Application
expertCalculate the product of all even numbers in an array
What is the output of this Java program that multiplies all even numbers in an array?
Java
public class Main { public static void main(String[] args) { int[] nums = {2, 3, 4, 5, 6}; int product = 1; for (int n : nums) { if (n % 2 == 0) { product *= n; } } System.out.println(product); } }
Attempts:
2 left
💡 Hint
Multiply only even numbers: 2, 4, and 6.
✗ Incorrect
2 * 4 = 8, 8 * 6 = 48, so output is 48.
