Bird
0
0

You have a list of names and want to print only those starting with 'J' using a for loop. Which code correctly does this?

hard📝 Application Q8 of 15
Kotlin - Loops and Ranges
You have a list of names and want to print only those starting with 'J' using a for loop. Which code correctly does this?
Afor (name in names) { if (name.startsWith("J")) println(name) }
Bfor (name in names) { if (name[0] == 'J') print(name) }
Cfor (name in names) println(name.startsWith("J"))
Dfor (name in names) { if (name.contains("J")) println(name) }
Step-by-Step Solution
Solution:
  1. Step 1: Check condition to filter names starting with 'J'

    Using name.startsWith("J") correctly checks the first letter.
  2. Step 2: Confirm printing only matching names

    for (name in names) { if (name.startsWith("J")) println(name) } prints the name only if it starts with 'J'. for (name in names) { if (name[0] == 'J') print(name) } prints without newline, C prints booleans, D checks contains which is incorrect.
  3. Final Answer:

    for (name in names) { if (name.startsWith("J")) println(name) } -> Option A
  4. Quick Check:

    Use startsWith to filter in for loop [OK]
Quick Trick: Use startsWith() inside for loop to filter items [OK]
Common Mistakes:
MISTAKES
  • Using contains instead of startsWith
  • Printing booleans instead of names
  • Not printing with newline

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Kotlin Quizzes