Pass array to functions in C++

Hello, Coders! In this tutorial, we will learn how to pass an Array as an argument to a function in C++.

In C++, an array can be passed to the functions just as the variables. We can pass the array by mentioning its name as well as by passing it as a pointer. In this process, only the starting address of the array gets passed to the function instead of the entire array.

Let’s discuss the ways to pass the Array as an argument:

  • Array as a pointer
  • Passing the array using its name

Array as a Pointer in C++

  • We can pass the array as a pointer to the function so that the address of the array can be accessed by the function.

Syntax:

datatype FunctionName(datatype *name_of_the_array) {
    -
    -
    -
    -
}

Example:

double avgMark(int *a, int numOfSub) {

  int i, sum = 0;
  double avg;

  for (i = 0; i < numOfSub; i++) {
    sum += a[i];
  }
  
  avg = double(sum) / numOfSub;
  return avg;
}

Let’s call the function in a program:

int main() {
    
  int numOfSub, a[100];

  cout << "Enter the Number Of Subject" << endl;
  cin >> numOfSub;
  
  cout << "Enter the Marks of the Subject respectively:" 
  << endl;
  
  for (int i = 0; i < numOfSub; i++) {
    cin >> a[i];
  }

  double avg;

  //Pass the array as a pointer
  avg = avgMark(a, numOfSub);

  cout << "The Average Mark Is: " << avg << endl;

  return 0;
}

Output:

Enter the Number Of Subject
5
Enter the Marks of the Subject respectively:
89
78
69
81
97
The Average Mark Is: 82.8

Passing the Array using its name in C++

  • We can also pass the array only by using its name only.

Note:  array[], array is same as the *array. The function treated the array name as a pointer. (a[ ] is same as the *a)

Syntax:

datatype FunctionName(datatype name_of_the_array[]) { 
    - 
    - 
    - 
    - 
}

Example:

double avgMark(int a[], int numOfSub) { 

  int i, sum = 0;
  double avg;

  for (i = 0; i < numOfSub; i++) {
    sum += a[i];
  }
  
  avg = double(sum) / numOfSub;
  return avg;
}

Calling the function in a program;

int main() {
    
  int numOfSub, a[100];

  cout << "Enter the Number Of Subject" << endl;
  cin >> numOfSub;
  
  cout << "Enter the Marks of the Subject respectively:" 
  << endl;
  
  for (int i = 0; i < numOfSub; i++) {
    cin >> a[i];
  }

  double avg;

  //Pass the array as a pointer
  avg = avgMark(a, numOfSub);

  cout << "The Average Mark Is: " << avg << endl;

  return 0;
}

Output:

Enter the Number Of Subject
5 
Enter the Marks of the Subject respectively:
78
59
71
69
58
The Average Mark Is: 67

Hope this article has helped you understand the concept of passing the array  to the function in C++.

Happy Coding!!

You can also read, Default arguments in the C++ function

Leave a Reply

Your email address will not be published. Required fields are marked *