Swift program to pass an array into a user-defined function

Here, we are going to learn how to pass an array into a user-defined function in Swift programming language?
Submitted by Nidhi, on June 24, 2021

Problem Solution:

Here, we will create a user-defined function that will accept an array as a parameter. Then we will return the sum of array elements.

Program/Source Code:

The source code to pass an array into a user-defined function is given below. The given program is compiled and executed successfully.

// Swift program to pass an array into 
// a user defined function

import Swift
func AddElements(arr: [Int]) -> Int {
    var sum = 0
    
    for item in arr {
        sum = sum + item
    }
    return sum
}

let arr:[Int] = [1,2,3,4,5,6,7,8]

var res = AddElements(arr:arr)

print("Sum of array elements is: ",res)

Output:

Sum of array elements is:  36

...Program finished with exit code 0
Press ENTER to exit console.

Explanation:

In the above program, we imported a package Swift to use the print() function using the below statement,

import Swift;

Here, we created a user-defined function AddElements(). The AddElements() function accepts an integer array as a parameter and returns the sum of array elements to the calling position and then we printed the result on the console screen.

Swift User-defined Functions Programs »






Comments and Discussions!

Load comments ↻






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