Continue
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 50 of 93.
While break exits a loop entirely, sometimes you only want to skip the current iteration and move on to the next one. The continue statement does exactly that.
When continue executes, the loop immediately jumps to the next iteration, skipping any remaining code in the current cycle:
for (i in 1..5) {
if (i == 3) {
continue
}
println(i)
}
// Output:
// 1
// 2
// 4
// 5Notice that 3 is missing from the output. When i equals 3, continue skips the println and moves directly to i = 4.
This is useful when you want to filter out certain values without stopping the entire loop. For example, printing only even numbers:
for (num in 1..6) {
if (num % 2 != 0) {
continue
}
println(num)
}
// Output:
// 2
// 4
// 6The key difference: break stops the loop completely, while continue only skips to the next iteration.
Challenge
MediumRead an integer n from input. Use a for loop to print all numbers from 1 to n, but skip any number that is divisible by 3.
Use the continue statement to skip the numbers divisible by 3.
For example, if the input is 10, the output should be:
1
2
4
5
7
8
10Notice that 3, 6, and 9 are missing because they are divisible by 3.
Try it yourself
fun main() {
// Read input
val n = readLine()!!.toInt()
// TODO: Write your code below
// Use a for loop to print numbers from 1 to n
// Skip numbers divisible by 3 using the continue statement
}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