Nested Loop
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 52 of 93.
You can place a loop inside another loop to create a nested loop. The inner loop runs completely for each iteration of the outer loop.
for (i in 1..2) {
for (j in 1..3) {
println("i=$i, j=$j")
}
}
// Output:
// i=1, j=1
// i=1, j=2
// i=1, j=3
// i=2, j=1
// i=2, j=2
// i=2, j=3When i is 1, the inner loop runs three times (j goes from 1 to 3). Then i becomes 2, and the inner loop runs three more times. This gives us 2 × 3 = 6 total iterations.
Nested loops are commonly used to create patterns or work with grid-like structures:
for (row in 1..3) {
for (col in 1..row) {
print("*")
}
println()
}
// Output:
// *
// **
// ***Here, the inner loop's range depends on the outer loop's variable, creating a triangle pattern. The print() function outputs without a newline, while println() moves to the next line after each row.
Challenge
MediumRead an integer n from input. Use nested loops to print a multiplication table for numbers 1 through n.
For each row i from 1 to n, print the products i * 1, i * 2, ..., i * n separated by spaces, followed by a newline.
For example, if the input is 3, the output should be:
1 2 3
2 4 6
3 6 9If the input is 4, the output should be:
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16Use print() with a space to output values on the same line, and println() to move to the next row.
Try it yourself
fun main() {
// Read input
val n = readLine()!!.toInt()
// TODO: Write your code below
// Use nested loops to print the multiplication table
// Use print() with a space for values on the same line
// Use println() to move to the next row
}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