Function Parameters and Return Values
Learn to use parameters and return values with user-defined functions in C++.
Function with parameters
The parameters are the input values for the function enclosed in ()
, provided in the function call as arguments. Multiple parameters are separated by ,
and each parameter must have a data type. The following function receives two int
parameters and displays their sum.
void showSum(int a, int b)
{
cout << a + b << endl;
}
The following is the function call sending 5
and 10
as arguments:
showSum(5,10);
#include <iostream>using namespace std;void showSum(int a, int b){cout << a+b << endl;}int main(){showSum(5,10); // Function callreturn 0;}
Array as a function parameter
An array can be received in a function as a parameter without specifying its size. Therefore, the function should receive the size as a separate parameter.
The following program demonstrates the use of an array as a function parameter:
#include <iostream>using namespace std;void getSum(int arr[], int size){int sum = 0;for (int i = 0; i < size; i++){sum += arr[i];}cout << sum << endl;}int main(){int nums[4] = {10,20,30,40};getSum(nums,4);return 0;}
In the program above, the function receives an array int arr[]
and its size int size
as parameters. We need the size to traverse through each element of the array. We have used a for
loop to calculate the sum of array elements in c
and displayed it. In main
, we declare an array of 4
elements {10,20,30,40}
and pass it ...