Start learning free

LESSON 131 OF 348 · LOOPS & CONDITIONALS

Positive Number in Array in Kotlin: Fixing the Buggy Code

Practice Read the full explanation

Inside the code editor we've tried to write a function that takes an array nums as argument and returns true if there exists at least one positive (greater than zero) number in the array; returns false otherwise.

So when we called the function for [-1, 2, 3], we expected our code to print:

Array has positive numbers

but it seems like we made some mistakes because when we run our code, it prints:

Array doesn't have positive numbers

Assignment:

Your task is to fix our function.

STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · LOOPS & CONDITIONALS

    Buggy Code Check For Positive Numbers in Kotlin, explained

    What the code is supposed to do

    The function checkForPositive takes an IntArray named nums and returns true if at least one element is greater than zero, and false otherwise. The helper mainFunction calls it with [-1, 2, 3] and prints a message, so the program should print Array has positive numbers.

    The code you start with doesn't compile:

    class Solution {
        fun checkForPositive(nums: IntArray): Boolean {
            for (num in nums) {
                if (num > 0) {
                    return true
                } else {
                    return false
                }
            }
        }
    
        // Do not change this code:
        fun mainFunction() {
            if (checkForPositive(intArrayOf(-1, 2, 3))) {
                println("Array has positive numbers")
            } else {
                println("Array doesn't have positive numbers")
            }
        }
    }
    

    What goes wrong

    There are two connected problems, and they come from the same misunderstanding about return.

    1. The loop decides after one element. Both branches of the if contain a return, so the first element settles the answer whatever the rest of the array holds. For [-1, 2, 3] the first element is -1. It isn't positive, so the function would return false at once, and the 2 and 3 would never be looked at.
    2. The function has a path with no return. After the loop, the function ends without a value. The compiler cannot be sure the loop will always return, because an empty array makes the loop body run zero times. A function declared to return a Boolean must end every path with a value, so the compiler reports missing return statement.

    The deeper point is about what one element can prove. A positive number proves the answer is true, because one is enough. A number that isn't positive proves nothing: the next element may still be positive. The array is known to have no positive number only after every element has been checked.

    Tracing both versions on [-1, 2, 3]

    The original code fails twice over in the same walk-through. Even if the compile error were somehow ignored, the first pass of the loop would give num = -1, the condition -1 > 0 would be false, and the else branch would return false. The function would end there, and the elements 2 and 3 would never be read.

    The fixed version behaves differently at each pass:

    1. num = -1: not positive, nothing happens, the loop continues.
    2. num = 2: positive, so the function returns true and the loop ends. The 3 is never read, and it doesn't need to be.

    This pattern, "return as soon as the answer is certain, otherwise decide after the loop", is the standard shape for any question of the form "does at least one element satisfy a condition?".

    Fixing it step by step

    1. Keep the true case inside the loop. When num > 0, return true immediately. That part of the code was already right.
    2. Remove the else branch. A non-positive element should do nothing, so the loop moves on to the next element.
    3. Add return false after the loop. It runs only when the loop finished without returning, which means no element was positive. This also gives the empty array its answer and satisfies the compiler.
    4. Leave mainFunction alone. With the fix, the call for [-1, 2, 3] passes -1, reaches 2, returns true and prints Array has positive numbers.

    The fixed code in Kotlin

    class Solution {
        fun checkForPositive(nums: IntArray): Boolean {
            for (num in nums) {
                if (num > 0) {
                    return true
                }
            }
            return false
        }
    
        fun mainFunction() {
            if (checkForPositive(intArrayOf(-1, 2, 3))) {
                println("Array has positive numbers")
            } else {
                println("Array doesn't have positive numbers")
            }
        }
    }
    

    Some details behind the fix:

    • Early return versus final return. A return inside the loop answers "found one". The return after the loop answers "found none". Each sits where its meaning is true.
    • The compiler checks all paths. Kotlin doesn't run your code to see whether a path is reachable with real data. It checks that every possible path through the function ends in a return (or a thrown exception) when the return type isn't Unit.
    • if as a condition. checkForPositive(...) returns a Boolean, so mainFunction can use the call directly as the if condition.
    • The apostrophe in the message. "Array doesn't have positive numbers" is an ordinary string. A single quote needs no escape inside double quotes.

    Edge cases and common mistakes

    • Zero is not positive. The condition is a strict >. For [-1, 0] the function returns false.
    • Empty array. The loop does nothing and the function returns false.
    • A positive number later in the array. It is found, however many non-positive numbers come first. For [-5, -2, 0, 7] the loop reaches 7 and returns true.
    • Fixing the compile error the wrong way. Adding return false after the loop while keeping the else { return false } branch makes the code compile, but the function still looks only at the first element. The compiler would accept it, and [-1, 2, 3] would still give false.

    Testing

    Run the function on a few arrays you choose yourself, not only on the one in mainFunction. A fix that passes one example can still be wrong for the others.

    Try these inputs with checkForPositive, each of which exercises a different path through the loop:

    • [-1, 2, 3] gives true: the positive number comes after a non-positive one.
    • [4, -2] gives true: the first element already decides.
    • [-3, -1, 0] gives false: the whole array is checked and nothing is positive.
    • [] gives false: only the final return false runs.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free