Do-While Loop
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 48 of 93.
The do-while loop is similar to the while loop, but with one key difference: it always executes the code block at least once before checking the condition.
Here's the structure:
var count = 1
do {
println(count)
count++
} while (count <= 3)
// Output:
// 1
// 2
// 3The code inside the do block runs first, then the condition is checked. If the condition is true, the loop repeats. This is useful when you need the code to run at least once regardless of the condition.
Consider this example where the condition is false from the start:
var x = 10
do {
println("This prints once!")
} while (x < 5)
// Output: This prints once!Even though x < 5 is false, the message still prints because the condition is checked after the first execution. With a regular while loop, nothing would print at all.
Challenge
MediumRead an integer n from input. Use a do-while loop to print all numbers from 1 to n, each on a separate line.
The loop should execute at least once, even if n is less than 1. In that case, it should still print 1.
For example, if the input is 4, the output should be:
1
2
3
4If the input is 0, the output should be:
1Try it yourself
fun main() {
val n = readLine()!!.toInt()
// TODO: Write your code below
// Use a do-while loop to print numbers from 1 to n
// Remember: the loop should execute at least once
}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