Menu
CoddyTech

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: 1

The 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 icon

Challenge

Easy

The 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler