ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

Problem Solution:

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.

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.

Scala User-defined Functions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.