Here, we will create an array of integer elements. Then we will use the take() method to get the specified number of elements of the array and print the result on the console screen.
Here, we will create an array of integer elements. Then we will use the take() method to get the specified number of elements of the array and print the result on the console screen.
// Scala program to get first n number of elements
// from the array
object Sample {
def main(args: Array[String]) {
var arr1 = Array(1, 2, 3, 4, 5);
var arr2 = arr1.take(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
1 2 3
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 take() method to get the 3 elements from starting from array arr1 and assigned to the array arr2. After that, we printed the result on the console screen.
Program/Source Code:
Here, we will create an array of integer elements. Then we will use the take() method to get the specified number of elements of the array and print the result on the console screen.
Output:
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 take() method to get the 3 elements from starting from array arr1 and assigned to the array arr2. After that, we printed the result on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer