0
0
Kotlinprogramming~20 mins

If as an expression returning value in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
If Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
}
Atrue
BSmaller or equal
CGreater
D10
Attempts:
2 left
💡 Hint
Remember that in Kotlin, if can return a value that you can assign to a variable.
Predict Output
intermediate
2: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"
A3
BOdd
CEven
Dtrue
Attempts:
2 left
💡 Hint
Check if the number is divisible by 2 without remainder.
🧠 Conceptual
advanced
2: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.
Aval result = if (a > b) a else b
Bval result = if a > b { a } else { b }
Cval result = if (a > b) { a } else
Dval result = if (a > b) a; else b
Attempts:
2 left
💡 Hint
Remember the syntax for if expressions requires parentheses and else branch.
Predict Output
advanced
2: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)
}
AC
BB
CF
DA
Attempts:
2 left
💡 Hint
Check each condition from top to bottom to see which one matches first.
Predict Output
expert
2: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")
}
Acount = 0, result = Non-positive
Bcount = 0, result = Positive
Ccount = 1, result = Non-positive
Dcount = 1, result = Positive
Attempts:
2 left
💡 Hint
Remember that ++count increments before comparison.