Opening the book…
In this section, we discuss how to create a user-defined function that uses an array as its input.
Example
Write a user-defined function that receives an integer array as its input. The function produces the sum of the numbers in the array as its output.
Find the sum of all the numbers in an array is not a new programming task. We have done it in Section 7.2. But we did it in the main(). Now, we will discuss how to get it done in a user-defined function.
Here is the code of this function along with a main() for testing purpose:

The function getSum() receives an integer array along with the array's length and calculates and returns the sum of the integers in the array it receives. Please note: when we specify one of the input is an array, we use a pair of square brackets with no number in between, thus, the function can take an array with various length. Also notice, when we use this function in the main() in Line 15, we only pass the name of the array along with the length of the array.
Example
Write a user-defined function that receives an integer array as its input. The function checks the array to see if there is a negative number in it. If there is one, then return a Boolean value true, otherwise return false.
Following is the code of the function along with main() for testing purpose:

From this example, we can see that the function can work with arrays with different lengths.
Example
Write a user-defined function that receives an integer array as its input. The function sorts the numbers in the array it receives in a ascending order.
We wrote a program that sort the numbers in an array in an ascending order in the previous section (Section 7.3). But we did it in main(). Now, we will create a user-defined function that will do the same job.
Following is the code of the function along with main() for testing purpose:

Line 4: Since this function only sort the array it receives, no return value is needed, so we declare such function as void.
Line 6: We only need to declare a variable t in the function for swapping purpose. The value of the variable length is coming from the second input of the function. The code of the nested looping statement is directly copy and paste from the previous program in the Section 7.3.
In main() we call this function twice in Line 22 and Line 23 with different arrays as their inputs.
The output of this program:

This page titled 7.4: User-Defined functions with an Array as its Input was last modified on Wed, 24 Dec 2025 20:37:23 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Jin He.
The book could not be loaded just now.