Start learning free

LESSON 130 OF 347 · LOOPS & CONDITIONALS

Positive Number in Array in C#: 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

    C# · LOOPS & CONDITIONALS

    Buggy Code Check For Positive Numbers in C#, explained

    What the code is supposed to do

    CheckForPositive(int[] nums) returns true if at least one number in the array is greater than zero, and false if there is none. The lesson's MainFunction calls it with {-1, 2, 3} and prints Array has positive numbers when the answer is true.

    public bool CheckForPositive(int[] nums) {
        foreach (int num in nums) {
            if (num > 0) {
                return true;
            } else {
                return false;
            }
        }
    }
    

    This version does not even build: the compiler stops with the error not all code paths return a value.

    What goes wrong

    There are two bugs, and they are connected.

    1. The loop decides after one element. Both branches of the if/else contain a return, so the method returns during the first pass. For {-1, 2, 3} the first number is -1, which is not positive, so the else returns false at once. The positive numbers 2 and 3 are never looked at. One number that is not positive says nothing about the rest of the array.
    2. The path after the loop has no return. The compiler checks every route through the method, including the one where the loop finishes (for an empty array it finishes immediately). Because both branches inside the loop return, it is easy to believe nothing can reach the end, but the compiler still sees a route past the loop and requires a value there.

    Fixing it step by step

    1. Remove the else branch. Finding a number that is not positive must not end the search.
    2. Keep return true in the if. A single positive number is enough to answer the question, so the method can stop there.
    3. Add return false; after the loop. Reaching that line means every number was checked and none was positive. This also gives the compiler its missing return.

    The fixed code in C#

    public bool CheckForPositive(int[] nums) {
        foreach (int num in nums) {
            if (num > 0) {
                return true;
            }
        }
        return false;
    }
    
    
    public void MainFunction() {
        if (CheckForPositive(new int[]{-1, 2, 3})) {
            Console.WriteLine("Array has positive numbers");
        } else {
            Console.WriteLine("Array doesn't have positive numbers");
        }
    }
    

    Tracing {-1, 2, 3}: -1 is not positive, so the if does nothing and the loop moves on. 2 is positive, so the method returns true immediately, and MainFunction prints:

    Array has positive numbers
    

    The pattern here is a general one. To ask "does at least one element have this property?", return true inside the loop as soon as you find it, and return false after the loop. To ask "do all elements have it?", flip the logic: return false on the first failure and true after the loop.

    Why the mistake is tempting

    The starter code reads naturally as a sentence: "if the number is positive, return true, otherwise return false". That sentence is right for a single number. For an array it hides a question: otherwise what? A non-positive number is only one element's answer, while the method has to answer for the whole array. A good habit is to ask, at each return inside a loop, whether the information seen so far is enough to settle the final answer. A positive number settles it, because one is enough. A non-positive number does not.

    Details in C#

    • The compiler enforces returns. A method with return type bool must return a value on every path. This error appears at build time, before the program runs.
    • Zero is not positive. The test is num > 0, so an array like {0, -3} gives false.
    • An empty array gives false: the loop body never runs, and there is no positive number.
    • Braces matter. Without braces, only the first statement after if belongs to it. Keeping braces on every branch avoids that trap.

    Common mistakes

    • Keeping the else and only adding a final return. The code then compiles, but still answers false for {-1, 2, 3}.
    • Returning false as the first statement after the loop's if but still inside the loop. The result is the same early exit.
    • Counting instead of returning. Some learners count the positive numbers in a variable and compare it with zero at the end. That works, but it keeps scanning after the answer is known. Returning early is shorter and stops sooner.
    • Using num >= 0. That would count zero as positive.

    Tracing the fix on three inputs

    • {-1, 2, 3}. The first pass skips -1. The second pass sees 2, which is greater than zero, and returns true. The 3 is never examined.
    • {-5, -2}. Both passes skip their element, the loop ends, and the final return false; runs.
    • {}. The loop body never runs, and the method goes straight to return false;.

    In all three cases the method returns exactly once, and the early return only happens when a positive number has really been found. That is the property the buggy version lacked: it returned before it had enough information.

    Checking your fix

    Read the finished method once from top to bottom, and confirm that it has exactly one way out of the loop early and one way out after it.

    Run the code. The editor should show Array has positive numbers. Also try, in your head, {-5, -2} (the answer is false), {0} (false) and {4} (true).

    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free