0
0
Javaprogramming~10 mins

Return inside loops in Java - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to return the first even number found in the array.

Java
public int findFirstEven(int[] numbers) {
    for (int num : numbers) {
        if (num % 2 == 0) {
            return [1];
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Anum + 1
Bnumbers
C0
Dnum
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the whole array instead of the number.
Returning a fixed number like 0 instead of the found number.
2fill in blank
medium

Complete the code to return true if any number in the array is negative.

Java
public boolean hasNegative(int[] numbers) {
    for (int num : numbers) {
        if (num < 0) {
            return [1];
        }
    }
    return false;
}
Drag options to blanks, or click blank then click option'
Anum
Btrue
Cfalse
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Returning false inside the loop.
Returning the number instead of a boolean.
3fill in blank
hard

Fix the error in the code to return the index of the first zero in the array, or -1 if none found.

Java
public int findFirstZero(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            return [1];
        }
    }
    return -1;
}
Drag options to blanks, or click blank then click option'
Ai
Barr[i]
C0
D-1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the value arr[i] instead of the index.
Returning a fixed number like 0.
4fill in blank
hard

Fill both blanks to return the sum of positive numbers in the array.

Java
public int sumPositive(int[] nums) {
    int sum = 0;
    for (int [1] = 0; [2] < nums.length; i++) {
        if (nums[i] > 0) {
            sum += nums[i];
        }
    }
    return sum;
}
Drag options to blanks, or click blank then click option'
Ai
Bnum
Cj
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in initialization and condition.
Using a variable that is not an integer index.
5fill in blank
hard

Fill all three blanks to return true if all numbers in the array are positive.

Java
public boolean allPositive(int[] arr) {
    for (int [1] = 0; [2] < arr.length; [3]++) {
        if (arr[i] <= 0) {
            return false;
        }
    }
    return true;
}
Drag options to blanks, or click blank then click option'
Ai
Bj
Dk
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in the for loop parts.
Using a variable not declared in the loop.