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:
Step 1: Check condition to filter names starting with 'J'
Using name.startsWith("J") correctly checks the first letter.
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.
Final Answer:
for (name in names) { if (name.startsWith("J")) println(name) } -> Option A
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
Master "Loops and Ranges" in Kotlin
9 interactive learning modes - each teaches the same concept differently