Bird
0
0

Given val nums = listOf(1, 2, 3, 4, 5, 6), which Kotlin code correctly uses forEach to print only the even numbers?

hard📝 Application Q8 of 15
Kotlin - Collections Fundamentals
Given val nums = listOf(1, 2, 3, 4, 5, 6), which Kotlin code correctly uses forEach to print only the even numbers?
Anums.forEach { println(it % 2 == 0) }
Bnums.forEach { if (it % 2 == 0) println(it) }
Cnums.forEach { println(it) if (it % 2 == 0) }
Dnums.forEach { if (it / 2 == 0) println(it) }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Print only even numbers from the list.
  2. Step 2: Analyze options

    nums.forEach { if (it % 2 == 0) println(it) } uses a conditional inside forEach to print only if the number is even.
  3. Step 3: Check other options

    nums.forEach { println(it % 2 == 0) } prints true/false for each element, not the number. nums.forEach { println(it) if (it % 2 == 0) } has invalid syntax. nums.forEach { if (it / 2 == 0) println(it) } uses incorrect condition.
  4. Final Answer:

    nums.forEach { if (it % 2 == 0) println(it) } -> Option B
  5. Quick Check:

    Use if inside forEach to filter elements [OK]
Quick Trick: Use if condition inside forEach to filter [OK]
Common Mistakes:
MISTAKES
  • Printing boolean instead of numbers
  • Incorrect if syntax inside lambda
  • Using division instead of modulo for even check

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes