Iterating With Indexes
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 70 of 92.
A loop over the elements gives you each value, but not its position. When you need the index too, loop over the indexes with range() and read each element with square brackets:
var fruits := ["apple", "banana", "orange"]
for i in range(fruits.size()):
print("Index %d: %s" % [i, fruits[i]])Index 0: apple
Index 1: banana
Index 2: orangerange(fruits.size()) gives 0, 1 and 2: exactly the indexes of the array. On each pass, i is the index and fruits[i] the element.
The index is also what lets you change the array inside a loop. Assigning to the loop variable of for price in prices: changes only that variable, while assigning to prices[i] changes the array:
var prices := [2, 5]
for i in range(prices.size()):
prices[i] *= 2
print(prices)[4, 10]Challenge
EasyThe program reads a line of whole numbers separated by commas into the array numbers (already written).
Print an array with the indexes of the numbers that are below 50 or divisible by 5. For the input 80,4,99,36,34:
80(index 0) is divisible by 5: included4(index 1) is below 50: included99(index 2): not included36(index 3) and34(index 4) are below 50: included
The output is:
[0, 1, 3, 4]Try it yourself
extends Node
func _ready():
var parts := OS.read_string_from_stdin().split(",")
var numbers: Array[int] = []
for part in parts:
numbers.append(int(part))
# Write your code below
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 Values13Iterating Over Arrays
Iterating Over ElementsIterating With IndexesIterating Over Strings Part 1Iterating Over Strings Part 25Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler