Bird
0
0

How can you use if as an expression to assign a message based on temperature, where temperature > 30 is "Hot", between 15 and 30 is "Warm", else "Cold"?

hard📝 Application Q9 of 15
Kotlin - Control Flow as Expressions
How can you use if as an expression to assign a message based on temperature, where temperature > 30 is "Hot", between 15 and 30 is "Warm", else "Cold"?
Aval message = if (temp > 30) "Hot" else if (temp >= 15) "Warm" else "Cold"
Bval message = if (temp > 30) "Hot" else if (temp > 15 && temp < 30) "Warm" else "Cold"
Cval message = if (temp > 30) "Hot" else if (temp > 15 || temp < 30) "Warm" else "Cold"
Dval message = if (temp > 30) "Hot" else if (temp > 15) "Warm" else "Cold"
Step-by-Step Solution
Solution:
  1. Step 1: Understand the temperature ranges

    Temperature > 30 is Hot, 15 to 30 inclusive is Warm, else Cold.
  2. Step 2: Check conditions in options

    val message = if (temp > 30) "Hot" else if (temp >= 15) "Warm" else "Cold" correctly uses >= 15 for warm range and else for cold. Others have incorrect logical operators or ranges.
  3. Final Answer:

    val message = if (temp > 30) "Hot" else if (temp >= 15) "Warm" else "Cold" -> Option A
  4. Quick Check:

    Use correct range checks in nested if expressions [OK]
Quick Trick: Use >= and else to cover all ranges in if expression [OK]
Common Mistakes:
MISTAKES
  • Using || instead of && for range
  • Missing inclusive boundary with >= or <=
  • Incorrect else placement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes