Kotlin - Loops and RangesHow can you use a for loop to create a new list of squares from an existing list of integers in Kotlin?Aval squares = numbers.forEach { it * it }Bval squares = mutableListOf<Int>(); for (n in numbers) { squares.add(n * n) }Cfor (n in numbers) { val squares = n * n }Dval squares = listOf<Int>(); for (n in numbers) { squares.add(n * n) }Check Answer
Step-by-Step SolutionSolution:Step 1: Initialize a mutable list to store resultsUse mutableListOf() to create an empty list that can be added to.Step 2: Loop through numbers and add squaresInside the loop, calculate n * n and add to squares list.Final Answer:val squares = mutableListOf(); for (n in numbers) { squares.add(n * n) } -> Option BQuick Check:Use mutable list and add inside loop [OK]Quick Trick: Use mutableListOf and add() inside for loop [OK]Common Mistakes:MISTAKESUsing immutable list and trying to addReinitializing list inside loopUsing forEach which returns Unit
Master "Loops and Ranges" in Kotlin9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Kotlin Quizzes Control Flow as Expressions - If as an expression returning value - Quiz 9hard Functions - Infix functions for readable calls - Quiz 15hard Kotlin Basics and JVM Runtime - Kotlin REPL and script mode - Quiz 10hard Kotlin Basics and JVM Runtime - Main function as entry point - Quiz 15hard Kotlin Basics and JVM Runtime - How Kotlin compiles to JVM bytecode - Quiz 13medium Loops and Ranges - Repeat function for simple repetition - Quiz 4medium Null Safety - Safe call operator (?.) - Quiz 10hard Variables and Type System - String templates and interpolation - Quiz 7medium Variables and Type System - Val for immutable references - Quiz 10hard Variables and Type System - Type checking with is operator - Quiz 1easy