While Loop
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 47 of 93.
While a for loop works great when you know the exact number of iterations, sometimes you need to keep looping until a certain condition changes. That's where the while loop comes in.
A while loop continues running as long as its condition is true:
var count = 1
while (count <= 3) {
println(count)
count++
}
// Output:
// 1
// 2
// 3The loop checks the condition before each iteration. Once count becomes 4, the condition count <= 3 is false, and the loop stops.
Be careful: if the condition never becomes false, you'll create an infinite loop. Always make sure something inside the loop eventually changes the condition:
var password = ""
while (password != "secret") {
password = readLine() ?: ""
}
println("Access granted!")This loop keeps asking for input until the user enters "secret". The while loop is ideal when you don't know in advance how many iterations you'll need.
Challenge
MediumRead an integer n from input. Use a while loop to print all numbers from n down to 1, each on a separate line.
For example, if the input is 5, the output should be:
5
4
3
2
1Try it yourself
fun main() {
val n = readLine()!!.toInt()
// TODO: Write your code below
// Use a while loop to print all numbers from n down to 1
}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