Q:

Scala program to pass an array into user-defined function

belongs to collection: Scala User-defined Functions Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to create a currying function to add... >>
<< Scala program to create a function with the defaul...