Ranges In Loops
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 51 of 93.
So far, we've used 1..5 to create ranges that count upward by one. Kotlin offers more flexible ways to define ranges for your loops.
To count backward, use downTo:
for (i in 5 downTo 1) {
println(i)
}
// Output: 5, 4, 3, 2, 1To skip numbers, add step to control the increment:
for (i in 0..10 step 2) {
println(i)
}
// Output: 0, 2, 4, 6, 8, 10You can combine downTo with step for backward counting with custom intervals:
for (i in 10 downTo 1 step 3) {
println(i)
}
// Output: 10, 7, 4, 1If you need to exclude the last value, use until instead of ..:
for (i in 1 until 5) {
println(i)
}
// Output: 1, 2, 3, 4The until keyword is especially useful when working with zero-based indices, where you often need to stop before reaching a certain number.
Challenge
MediumRead two integers from input: start and end.
Print all even numbers from start down to end (inclusive), each on a separate line.
Use downTo with step to create the range. If start is odd, begin from the first even number below it.
For example, if the input is:
10
2The output should be:
10
8
6
4
2If the input is:
9
3The output should be:
8
6
4If there are no even numbers in the requested range, print No even numbers on one line. Otherwise, print each even number on its own line.
Try it yourself
fun main() {
// Read input
val start = readLine()!!.toInt()
val end = readLine()!!.toInt()
// TODO: Write your code below
// Use downTo with step to print all even numbers from start down to end
// If start is odd, begin from the first even number below it
}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