Scala program to get the last N number of elements from the array

Here, we are going to learn how to get the last N number of elements from the array in Scala programming language?
Submitted by Nidhi, on May 25, 2021 [Last updated : March 10, 2023]

Scala – Last N Elements of an Array

Here, we will create an array of integer elements. Then we will use takeRight() method to get the last specified number of elements of the array and print the result on the console screen.

Scala code to print the last N number of elements from the array

The source code to get the last N number of elements from the array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to get the last N number
// of elements from array

object Sample {
  def main(args: Array[String]) {
    var arr1 = Array(1, 2, 3, 4, 5);
    var arr2 = arr1.takeRight(3);

    var i: Int = 0;

    printf("Elements of arr2\n");
    while (i < arr2.length) {
      printf("%d ", arr2(i));
      i = i + 1;
    }
    println();
  }
}

Output

Elements of arr2
3 4 5

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created an array arr1 that contains 5 integer elements. Then we used the takeRight() method to get the last 3 elements from array arr1 and assigned them to the array arr2. After that, we printed the result on the console screen.

Scala Array Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.