Start learning free

LESSON 131 OF 415 · LOOPS & CONDITIONALS

Print Even Numbers 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 prints to the console the even numbers from that array.

So when we called printEvenNumbers([2, 1, 0, 4, 3]), we expected our code to print:

2
0
4

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

even
even

Assignment:

Your task is to fix our function such that it prints the even numbers from the array.

STEP 1 OF 1
    Ctrl + Enter to check

    SWIFT · LOOPS & CONDITIONALS

    Buggy Code Print Even Numbers in Swift, explained

    What the code should do

    The function printEvenNumbers(_ nums: [Int]) should print the even numbers of an array, one per line. The call printEvenNumbers([2, 1, 0, 4, 3]) is expected to print 2, 0 and 4. Instead, the code prints the word even twice. Here is the starting code:

    func printEvenNumbers(_ nums: [Int]) {
        for num in nums {
            if num % 2 == 1 {
                print("even")
            }
        }
    }
    

    There are two separate mistakes, both inside the loop.

    Mistake 1: the condition selects odd numbers

    The remainder operator % gives what is left after a division. An even number divides by 2 with nothing left over, so num % 2 is 0. An odd number leaves 1. The condition num % 2 == 1 is therefore true for the odd numbers, 1 and 3 in the example, and false for 2, 0 and 4.

    That explains why the output has two lines: the array has two odd numbers, and the if body runs once for each. The fix is to compare with 0: num % 2 == 0.

    Mistake 2: printing text instead of the value

    Text inside double quotes is a string literal. print("even") writes the characters e-v-e-n every time, whatever num holds. The task asks for the numbers themselves, so the call must pass the variable, without quotes: print(num).

    Tracing the original code

    Following the starting code through the array shows both bugs at once:

    numnum % 2Condition == 1Output
    20falsenothing
    11trueeven
    00falsenothing
    40falsenothing
    31trueeven

    The table matches the reported output exactly, two lines of even. Tracing a few values by hand like this is the quickest way to find the cause of a wrong output.

    Fixing it step by step

    1. Read the output. Two lines of even for five numbers means the body ran for two of them, and the text is fixed.
    2. Check which numbers get through. Trace num % 2 == 1 for 2, 1, 0, 4, 3. It is true only for 1 and 3, so the condition picks odd numbers.
    3. Change the condition to num % 2 == 0.
    4. Change the print call to print(num).
    5. Leave the rest alone. The loop, the function name and mainFunction are correct.

    The fixed code in Swift

    func printEvenNumbers(_ nums: [Int]) {
        for num in nums {
            if num % 2 == 0 {
                print(num)
            }
        }
    }
    
    
    func mainFunction() {
        printEvenNumbers([2, 1, 0, 4, 3])
    }
    

    Now the call prints 2, 0 and 4, in the order they appear in the array.

    Swift details worth knowing:

    • 0 is even. Zero divided by 2 leaves no remainder, so it is printed.
    • Negative numbers. In Swift the remainder takes the sign of the left operand, so -3 % 2 is -1, not 1. A test like num % 2 == 1 would therefore miss negative odd numbers too. Comparing with 0 gives the right answer for positive and negative numbers alike: -4 % 2 is 0.
    • Unlabeled parameter. The _ in _ nums means the call is written printEvenNumbers([...]), with no label.

    Common mistakes

    • Fixing only one bug. With == 0 and print("even"), the program prints even three times, once for each of 2, 0 and 4.
    • With print(num) but == 1. The program prints the odd numbers 1 and 3.
    • Using = instead of ==. A single = is assignment, and Swift rejects it as a condition.
    • Using / instead of %. Integer division gives the quotient, not the remainder.

    Checking your fix

    Try your function in the editor above with a few arrays. [2, 1, 0, 4, 3] prints 2, 0 and 4. [-4, -3] prints -4. An empty array prints nothing.

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