Scala program to pass an array into user-defined function

Here, we are going to learn how to pass an array into user-defined function in Scala programming language?
Submitted by Nidhi, on May 27, 2021 [Last updated : March 09, 2023]

Scala – Passing an array into function

Here, we will define a function. And, we will pass an integer array as an argument and print the array elements on the console screen.

Scala code to pass an array into user-defined function

The source code to create a function with the default value for non-trailing arguments is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to pass an array
// into user defined function

object Sample {
  def main(args: Array[String]) {
    var arr = Array(1, 2, 3, 4, 5);
    // Function calling
    printArray(arr);
  }
  
  // unction definition
  def printArray(arr: Array[Int]) {
    var i: Int = 0;

    println("Elements of array:");
    while (i < arr.length) {
      printf("%d ", arr(i));
      i = i + 1;
    }
    println();
  }
}

Output

Elements of array:
1 2 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 this program, we defined a function printArray() with array as an argument to print array elements on the console screen.

In the main() function, we created an array arr with integer elements. Then we called the printArray() function to print array elements on the console screen.

Scala User-defined Functions Programs »





Comments and Discussions!

Load comments ↻





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