Menu
CoddyTech

Nested Loops with 2D Arrays

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 14 of 78.

To visit every cell of a 2D array, put one loop inside another. The outer loop goes through the rows, and the inner loop goes through the cells of the current row:

var grid := [[1, 2, 3], [4, 5, 6]]
var total := 0
for row in grid:
	for cell in row:
		total += cell
print(total) # 21

When you need the position of each cell, loop over the indices. r is the row index, c the column index, and the inner loop uses grid[r].size(), the length of the current row:

for r in range(grid.size()):
	for c in range(grid[r].size()):
		grid[r][c] *= 10
print(grid) # [[10, 20, 30], [40, 50, 60]]

Assigning to cell in a for cell in row loop does not change the grid, because cell holds a copy of the number. Change cells through their indices, as above.

Nested loops also build a grid. Create a new row inside the outer loop, fill it in the inner loop, then append it:

var town := []
for r in range(3):
	var row := []
	for c in range(4):
		row.append(".")
	town.append(row)
town[1][2] = "P"
for row in town:
	print("".join(row))
....
..P.
....

The row must be created inside the outer loop. An array is shared, not copied, when you append it: if you append the same row three times, the three rows are one array, and town[1][2] = "P" puts a P in every row.

challenge icon

Challenge

Easy

Draw the map of a town. The program reads four whole numbers, one per line: the number of rows, the number of columns, the row of the player and the column of the player. The player position is always inside the map.

  1. Build grid, a 2D array with that many rows and columns, where every cell is ".". Use nested loops, and create a new row array for each row.
  2. Set the cell at the player position to "P".
  3. Print the map, one row per line, with no spaces between the cells.

For the inputs 3, 4, 1 and 2, the output is:

....
..P.
....

Try it yourself

extends Node

func _ready():
	var rows := int(OS.read_string_from_stdin())
	var cols := int(OS.read_string_from_stdin())
	var player_row := int(OS.read_string_from_stdin())
	var player_col := int(OS.read_string_from_stdin())
	var grid := []

	# Build the grid with nested loops

	# Put the player on the map

	# Print the map
	pass
quiz iconTest yourself

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

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler