Scala program to demonstrate the copyToArray() method

Here, we are going to demonstrate the copyToArray() method in Scala programming language.
Submitted by Nidhi, on May 20, 2021 [Last updated : March 10, 2023]

Scala – Array.copyToArray() Method

Here, we will create two arrays of integer elements. Then we will use the copyToArray() method to copy elements from one array to another array.

Scala code to demonstrate the example of Array.copyToArray() method

The source code to demonstrate the copyToArray() method is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate
// the copyToArray() method

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

    var i: Int = 0;

    arr1.copyToArray(arr2, 1, 3);
    printf("Elements of Array 'arr1':\n")
    i = 0;
    while (i < 5) {
      printf("%d ", arr1(i));
      i = i + 1;
    }
    println();

    printf("Elements of Array 'arr2':\n")
    i = 0;
    while (i < 5) {
      printf("%d ", arr2(i));
      i = i + 1;
    }
    println();
  }
}

Output

Elements of Array 'arr1':
1 2 3 4 5 
Elements of Array 'arr2':
5 1 2 3 1

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 two arrays of integers. Then we used copyToArray() method to copy 3 elements from arr1 at index 1 to array arr2. After that, we printed both arrays on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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