Nested Loop
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 49 of 92.
A nested loop is a loop inside another loop. For every iteration of the outer loop, the inner loop runs all of its iterations:
for i in range(3):
print("Outer: ", i)
for j in range(2):
print(" Inner: ", j)Outer: 0
Inner: 0
Inner: 1
Outer: 1
Inner: 0
Inner: 1
Outer: 2
Inner: 0
Inner: 1The inner block is indented two levels. It runs 3 x 2 = 6 times in total.
The two loops need different variable names. Writing for i inside another for i is an error, reported before the program runs.
Nested loops are useful for rows and columns. print() always ends the line, so to print a row of stars, build it in a string first and print it once the inner loop is done:
for row in range(2):
var line := ""
for col in range(3):
line += "*"
print(line)***
***The outer loop runs once per row, and the inner loop adds one star per column. A break inside the inner loop stops only the inner loop: the outer loop goes on with its next iteration.
Challenge
EasyThe program reads two whole numbers: rows and cols.
Use nested loops to print a rectangle of stars (*) with rows lines and cols stars on each line.
For the inputs 3 and 4, the output is:
****
****
****Try it yourself
extends Node
func _ready():
var rows := int(OS.read_string_from_stdin())
var cols := int(OS.read_string_from_stdin())
# Outer loop: one iteration per row
# Inner loop: add one star per column
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler