CommencerCommencer gratuitement

Looping over ranges

Now that you can define a UnitRange and StepRange, let's look at how you can iterate over these ranges using the two loops covered in this chapter. You saw previously that if you just print the variable, you get the range itself, not the values within the range. To get the values within the range, you can use a loop to iterate over each value in the range.

A range allows us to set a starting point, and this can be useful if you are not actually looping over a range itself but instead looping over another data type, using a range to specify where to slice.

In the first part of this exercise, you will define a range my_range, and then use a for loop to print all values in that range. For the second part of this exercise, you will iterate over the same range but using a while loop.

Cet exercice fait partie du cours

Intermediate Julia

Afficher le cours

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Define a range with start=1, stop=100, step=5
my_range = ____:____:____

# Iterate over my_range using a for loop, print results
for ____ in ____
	println(____)
end
Modifier et exécuter le code