Challenge - 5 Problems
If Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using if as an expression?
Consider the following Kotlin code snippet. What will be printed when it runs?
Kotlin
fun main() { val x = 10 val result = if (x > 5) "Greater" else "Smaller or equal" println(result) }
Attempts:
2 left
💡 Hint
Remember that in Kotlin, if can return a value that you can assign to a variable.
✗ Incorrect
The if expression checks if x is greater than 5. Since 10 is greater than 5, it returns "Greater" which is assigned to result and printed.
❓ Predict Output
intermediate2:00remaining
What value does the variable 'message' hold after this code runs?
Look at this Kotlin code. What is the value of 'message' after execution?
Kotlin
val number = 3 val message = if (number % 2 == 0) "Even" else "Odd"
Attempts:
2 left
💡 Hint
Check if the number is divisible by 2 without remainder.
✗ Incorrect
3 % 2 equals 1, which is not zero, so the else branch "Odd" is assigned to message.
🧠 Conceptual
advanced2:00remaining
Which Kotlin code snippet correctly uses if as an expression to assign a value?
Select the option that correctly uses if as an expression returning a value in Kotlin.
Attempts:
2 left
💡 Hint
Remember the syntax for if expressions requires parentheses and else branch.
✗ Incorrect
Option A correctly uses if as an expression with parentheses and else branch returning values. Other options have syntax errors.
❓ Predict Output
advanced2:00remaining
What is the output of this Kotlin code using nested if expressions?
Analyze the code and choose the output printed.
Kotlin
fun main() { val score = 75 val grade = if (score >= 90) "A" else if (score >= 80) "B" else if (score >= 70) "C" else "F" println(grade) }
Attempts:
2 left
💡 Hint
Check each condition from top to bottom to see which one matches first.
✗ Incorrect
Score 75 is not >= 90 or 80 but is >= 70, so the grade is "C".
❓ Predict Output
expert2:00remaining
What is the output of this Kotlin code using if expression with side effects?
Consider this Kotlin code. What will be printed when it runs?
Kotlin
fun main() { var count = 0 val result = if (++count > 0) { "Positive" } else { "Non-positive" } println("count = $count, result = $result") }
Attempts:
2 left
💡 Hint
Remember that ++count increments before comparison.
✗ Incorrect
++count increments count from 0 to 1 before comparison, so condition is true and result is "Positive".