Start learning free

LESSON 129 OF 348 · LOOPS & CONDITIONALS

Print Positive and Negative 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 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

    KOTLIN · LOOPS & CONDITIONALS

    Buggy Code Print Positive Negative in Kotlin, explained

    What the code is supposed to do

    The function printPositiveAndNegative receives an IntArray named nums and prints exactly one line for each element. If the number is below zero, the line is the word negative. Otherwise the line is the number itself. Zero counts as "otherwise", so it is printed as 0.

    For [2, -12, 0, 4, -5, 3] the expected output is:

    2
    negative
    0
    4
    negative
    3
    

    The code you start with produces nine lines instead of six:

    fun printPositiveAndNegative(nums: IntArray) {
        for (num in nums) {
            if (num > 0) {
                println("positive")
            }
            println(num)
        }
    }
    

    What goes wrong

    There are two separate mistakes in the loop body.

    1. The condition is for the wrong numbers. num > 0 is true for the positive numbers, so they get an extra line saying positive. The special message was meant for the numbers below zero, and the word was meant to be negative.
    2. The final println(num) is unconditional. It sits after the if, not inside a branch, so it runs for every element. A positive number therefore produces two lines, the message and the number itself, and a negative number is printed as -12 instead of negative.

    Tracing the first three elements shows the effect. For 2 the condition is true, so the output is positive then 2. For -12 the condition is false and only -12 is printed. For 0 the condition is false as well, since zero is not greater than zero, and only 0 is printed. That matches the nine wrong lines the starting code prints: positive, 2, -12, 0, positive, 4, -5, positive, 3.

    Fixing it step by step

    1. Decide which case gets which output. Below zero prints negative. Everything else prints the number. Two cases that are exclusive and cover every number call for if and else.
    2. Change the condition from num > 0 to num < 0, so that it is true exactly for the negative numbers.
    3. Change the message to "negative".
    4. Move the number's print into an else branch. The two branches are alternatives, so each element now produces exactly one line.

    The fixed code in Kotlin

    fun printPositiveAndNegative(nums: IntArray) {
        for (num in nums) {
            if (num < 0) {
                println("negative")
            } else {
                println(num)
            }
        }
    }
    
    
    fun mainFunction() {
        printPositiveAndNegative(intArrayOf(2, -12, 0, 4, -5, 3))
    }
    

    A few details about this code:

    • Looping over an array. for (num in nums) gives each element in order, with no index to manage.
    • IntArray and intArrayOf. IntArray is Kotlin's array of primitive Int values, and intArrayOf(...) builds one. It is not the same type as Array<Int> or List<Int>, so a function declared with IntArray doesn't accept the other two.
    • println accepts any value. It prints a string as it is and turns an Int into its decimal text, so both branches can use the same function.
    • Quotes decide what is printed. println("negative") prints the word, while println(negative) would be a compile error because no variable has that name.

    Edge cases and common mistakes

    • Zero. Because the condition is a strict <, zero goes to the else branch and is printed as 0. Writing num <= 0 would print negative for zero, which is wrong for this task.
    • Empty array. The loop body never runs, so nothing is printed.
    • Keeping the old condition. Flipping only the message to negative while keeping num > 0 would label the positive numbers as negative.
    • Forgetting the else. Changing the condition and message but leaving println(num) after the if still prints both lines for a negative number: negative and then -12.

    The general lesson is that a statement placed after an if runs on every pass, whatever the condition said. Put it in a branch whenever it should run only for some of the values.

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