Home »
VB.Net »
VB.Net Programs
VB.Net program to pass an array into user define the function
By Nidhi Last Updated : November 15, 2024
Pass an array to VB.Net function
Here, we will create a user-defined function and pass an integer array as an argument. Here we will calculate the sum of all elements of the array and return the result to the calling function.
Program/Source Code:
The source code to pass an array into user define function is given below. The given program is compiled and executed successfully.
VB.Net code to demonstrate the example of passing an array to the function
'VB.Net program to pass an array into user-defined function.
Module Module1
Function AddNum(ByVal arr() As Integer) As Integer
Dim result As Integer = 0
For i = 0 To arr.Length - 1 Step 1
result = result + arr(i)
Next
AddNum = result
End Function
Sub Main()
Dim result As Integer = 0
Dim arr() As Integer = New Integer(5) {1, 2, 3, 4, 5, 6}
result = AddNum(arr)
Console.WriteLine("Sum is: {0}", result)
End Sub
End Module
Output
Sum is: 21
Press any key to continue . . .
Explanation
In the above program, we created a module Module1 that contain a sub-routines Main() and a user define function AddNum().
The Main() subroutine is the entry point for the program. Here, we created an array of 6 elements. Here, we passed array arr to the AddNum() function.
The AddNum() function accepts the integer array as an argument, here we calculated the sum of all array elements and then print the result on the console screen.
VB.Net User-defined Functions Programs »