July 2017
Intermediate to advanced
796 pages
18h 55m
English
An array is a mutable collection. In arrays, the order of the elements will be preserved and duplicated elements will be kept. Being mutable, you can change the value of any element of the array by accessing it by its index number. Let's demonstrate arrays with several examples. Use the following line of code to just declare a simple array:
val numbers: Array[Int] = Array[Int](1, 2, 3, 4, 5, 1, 2, 3, 3, 4, 5) // A simple array
Now, print all the elements of the array:
println("The full array is: ") for (i <- numbers) { print(" " + i) }
Now, print a particular element: for example, element 3:
println(numbers(2))
Let's sum all the elements and print the sum:
var total = 0;for (i <- 0 to (numbers.length - 1)) { total = total + numbers(i) ...Read now
Unlock full access