Start learning free

LESSON 148 OF 348 · LOOPING OVER ARRAY INDICES

Manipulating Array Elements Inside a For Loop in Scala in Scala

Lesson

Suppose you have an array nums and your task is to increment every number in that array by one.

The first idea that might come to your mind is to write a for loop like this:

val nums = Array(1, 2, 3)

// Increment items:
for (num <- nums) {
  var copy = num
  copy += 1
}

// Print the array after:
for (num <- nums) {
  println(num)
}

but when you run this code, you'll be surprised to see that the output is:

1
2
3

No element in nums changed its value. How is this possible since we clearly do num++ for every num in nums?


Let's talk about copies:

Take a look at this code:

var number = 100

var number_copy = number

number_copy++

println(number_copy) // Output: 101
println(number) // Output: 100

Although we wrote var number_copy = number, this doesn't mean that number and number_copy are one and the same.

number_copy is a completely different entitity (stored at a different memory address) than number.

What we did is initialize this new number_copy entity with the value of number. That's why we say the number_copy is a copy of number.

And so number_copy++ will only increment number_copy and won't have any effect on number.


The loop variable is just a copy:

This is what also happens with a for loop.

Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.

This code

val nums = Array(1, 2, 3)

for (num <- nums) {
  var copy = num
  copy += 1
}

works exactly like this code:

val nums = Array(1, 2, 3)

var num = nums(0)
num += 1

num = nums(1)
num += 1

num = nums(2)
num += 1

Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.

You'll see this better if we also print the value of num on each iteration.

val nums = Array(1, 2, 3)

for (num <- nums) {
  val copy = num + 1
  println(copy)
}

// Print the array after:
for (num <- nums) {
  println(num)
}

The output of this code is:

2
3
4
1
2
3

Looping over the indices:

In order to manipulate the entries of some array we have to loop over the items' indices:

val nums = Array(1, 2, 3)

for (index <- nums.indices) {
  nums(index) += 1
}

This code works exactly like this one:

val nums = Array(1, 2, 3)

var index = 0
nums(index) += 1

index += 1
nums(index) += 1

index += 1
nums(index) += 1

In this way we directly manipulate the actual entries of the list (nums(0), nums(1), etc.)

Assignment:

Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.

STEP 1 OF 1
    Ctrl + Enter to check

    Buggy Code Manipulate Array 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