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.
- The loop decides after one element. Both branches of the
ifcontain areturn, 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 returnfalseat once, and the2and3would never be looked at. - 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 aBooleanmust end every path with a value, so the compiler reportsmissing 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:
num = -1: not positive, nothing happens, the loop continues.num = 2: positive, so the function returnstrueand the loop ends. The3is 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
- Keep the
truecase inside the loop. Whennum > 0, returntrueimmediately. That part of the code was already right. - Remove the
elsebranch. A non-positive element should do nothing, so the loop moves on to the next element. - Add
return falseafter 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. - Leave
mainFunctionalone. With the fix, the call for[-1, 2, 3]passes-1, reaches2, returnstrueand printsArray 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
returninside the loop answers "found one". Thereturnafter 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'tUnit. ifas a condition.checkForPositive(...)returns aBoolean, somainFunctioncan use the call directly as theifcondition.- 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 returnsfalse. - 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 reaches7and returnstrue. - Fixing the compile error the wrong way. Adding
return falseafter the loop while keeping theelse { 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 givefalse.
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]givestrue: the positive number comes after a non-positive one.[4, -2]givestrue: the first element already decides.[-3, -1, 0]givesfalse: the whole array is checked and nothing is positive.[]givesfalse: only the finalreturn falseruns.