Bird
0
0

Given a variable num, write a when expression that returns "Even" if num is divisible by 2, "Odd" if divisible by 3, and "Other" otherwise. Which code is correct?

hard📝 Application Q9 of 15
Kotlin - Control Flow as Expressions
Given a variable num, write a when expression that returns "Even" if num is divisible by 2, "Odd" if divisible by 3, and "Other" otherwise. Which code is correct?
Aval result = when { num / 2 == 0 -> "Even" num / 3 == 0 -> "Odd" else -> "Other" }
Bval result = when (num) { 2 -> "Even" 3 -> "Odd" else -> "Other" }
Cval result = when { num % 2 == 0 -> "Even" num % 3 == 0 -> "Odd" else -> "Other" }
Dval result = when { num % 2 = 0 -> "Even" num % 3 = 0 -> "Odd" else -> "Other" }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the conditions for divisibility

    Divisible by 2 means remainder zero with %, same for 3.
  2. Step 2: Check syntax correctness

    val result = when { num % 2 == 0 -> "Even" num % 3 == 0 -> "Odd" else -> "Other" } uses correct conditions and arrows; val result = when (num) { 2 -> "Even" 3 -> "Odd" else -> "Other" } matches exact values incorrectly; val result = when { num / 2 == 0 -> "Even" num / 3 == 0 -> "Odd" else -> "Other" } uses division instead of modulo; val result = when { num % 2 = 0 -> "Even" num % 3 = 0 -> "Odd" else -> "Other" } uses assignment (=) instead of comparison (==).
  3. Final Answer:

    val result = when { num % 2 == 0 -> "Even" num % 3 == 0 -> "Odd" else -> "Other" } -> Option C
  4. Quick Check:

    Use modulo (%) and == for conditions in when [OK]
Quick Trick: Use modulo (%) and == for divisibility checks in when [OK]
Common Mistakes:
MISTAKES
  • Using division instead of modulo
  • Using single = instead of ==
  • Matching exact values instead of conditions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes