Start learning free

LESSON 134 OF 415 · LOOPS & CONDITIONALS

Print Positive / Negative in Swift: 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 for every number in the array:

  • prints "negative" if that number is less than zero

  • or prints the number itself, if the number is greater than or equal to zero

So when we called the function for [2, -12, 0, 4, -5, 3], we expected it to print:

2
negative
0
4
negative
3

but it seems like we made some mistakes because when we run our code, it produces this output:

positive
2
-12
0
positive
4
-5
positive
3

Assignment:

Your task is to fix our loop such that it will print the desired output.

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · LOOPS & CONDITIONALS

    Buggy Code Print Positive Negative in Swift, explained

    What the code is supposed to do

    The function printPositiveAndNegative receives an array nums. For each number it must print exactly one line: the word negative if the number is less than zero, or the number itself otherwise. For [2, -12, 0, 4, -5, 3] the output should be 2, negative, 0, 4, negative, 3.

    The starter code does something different:

    func printPositiveAndNegative(_ nums: [Int]) {
        for num in nums {
            if num > 0 {
                print("positive")
            }
            print(num)
        }
    }
    

    On the same array it prints positive, 2, -12, 0, positive, 4, -5, positive, 3.

    What goes wrong

    There are two separate problems in the loop body.

    1. The condition picks the wrong numbers. num > 0 is true for positive numbers, so they get an extra line saying positive. The special message was meant for numbers below zero, and the word was meant to be negative.
    2. The final print(num) is unconditional. It sits after the if block, so it runs for every number, including the ones that already got a message. That is why -12 and -5 appear as plain numbers instead of the word negative.

    The task needs each number to produce one line, either the message or the value, never both. That is a choice between two alternatives, and the tool for it is if with an else.

    Tracing the starter code

    Following the first three numbers makes the pattern visible. For 2, the test 2 > 0 is true, so the code prints positive, and then the unconditional line prints 2. For -12, the test is false, so nothing is printed by the if, and the last line prints -12. For 0, the test is false again, and 0 is printed, which happens to be correct. Every positive number therefore produces two lines and every negative number is printed as it is, which matches the wrong output exactly.

    Fixing it step by step

    1. Change the test to num < 0. Only strictly negative numbers get the message. Zero is not less than zero, so it is printed as a number, as the expected output shows.
    2. Print "negative" inside the if. The message is a string literal, so the quotes stay.
    3. Move print(num) into an else branch. It now runs only when the number is zero or positive.

    The fixed code in Swift

    func printPositiveAndNegative(_ nums: [Int]) {
        for num in nums {
            if num < 0 {
                print("negative")
            } else {
                print(num)
            }
        }
    }
    
    
    func mainFunction() {
        printPositiveAndNegative([2, -12, 0, 4, -5, 3])
    }
    

    The output is:

    2
    negative
    0
    4
    negative
    3
    

    Swift details worth knowing:

    • print adds a newline. Each call produces its own line, which is why one call per number gives one line per number.
    • Conditions need no parentheses, but braces are required around every branch, even a single statement.
    • else is exact. It runs when the if condition is false, which here means num >= 0. There is no need to write that second test.
    • Printing an Int and a String. print accepts any value, so the two branches can print different types.

    Notice how the shape of the code changed. In the starter, the if adds an extra action before a line that always runs. In the fix, the two actions are alternatives, and exactly one of them runs for each number. Whenever a task says "print this or that", look for an if/else rather than an if followed by an unconditional statement.

    Edge cases and common mistakes

    • Zero. Using num <= 0 would print negative for 0, which the expected output doesn't do.
    • Two ifs instead of if/else. An if num < 0 followed by a separate if num >= 0 also works, but else is shorter and can't leave a gap between the conditions.
    • Empty array. The loop body never runs and nothing is printed.
    • Spelling. The output must be exactly negative, in lowercase.

    Testing

    • [2, -12, 0, 4, -5, 3] prints 2, negative, 0, 4, negative, 3.
    • [] prints nothing.
    • [0] prints 0.
    • [-1] prints negative.
    Keep going with SwiftAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free