Start learning free

LESSON 145 OF 348 · LOOPING OVER ARRAY INDICES

Looping through an array using indices in Scala in Scala

Lesson

In some instances, we will want to loop through an array using indices.

The indices of an array meals are all the integer values from 0 to meals.length - 1, so we can iterate over them using an index variable i:

val meals = Array("pancakes", "pasta", "pizza", "avocado")

for (i <- meals.indices) {
	println("Meal number " + (i + 1) + " is " + meals(i) + ".")
}

The output of this code is:

Meal number 1 is pancakes.
Meal number 2 is pasta.
Meal number 3 is pizza.
Meal number 4 is avocado.

Assignment
Now let's print the temperature on each day, in this format:

On day 1 the temperature is 10.

On day 2 the temperature is 60.

...


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    Looping Through Arrays With Indices in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free