For Loop
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 46 of 93.
Sometimes you need to repeat an action multiple times. Instead of writing the same code over and over, you can use a loop. The for loop is perfect when you know exactly how many times you want to repeat something.
Here's the basic structure:
for (i in 1..5) {
println(i)
}This prints the numbers 1 through 5. The variable i takes each value in the range, and the code inside the curly braces runs for each value.
You can use any variable name, not just i:
for (number in 1..3) {
println("Count: $number")
}
// Output:
// Count: 1
// Count: 2
// Count: 3The loop variable only exists inside the loop. Each iteration, it automatically updates to the next value in the range until there are no more values left.
Challenge
MediumRead an integer n from input. Use a for loop to print all numbers from 1 to n, each on a separate line.
For example, if the input is 4, the output should be:
1
2
3
4Try it yourself
fun main() {
val n = readLine()!!.toInt()
// TODO: Write your code below to print numbers from 1 to n using a for loop
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground