Passing Array To Function In C

If you want to pass a single-dimension array as an argument in a function, you would have to declare a formal parameter in one of following three ways and all three declaration methods produce similar results because each tells the compiler that an integer pointer is going to be received. Similarly, you can pass multi-dimensional arrays as formal parameters.

Consider the following syntax to pass an array to the function.

Functionname(Arrayname); /* passing array */

1 Way:

return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

2 Way:

return_type function(type arrayname[SIZE])

3 Way:

return_type function(type *arrayname)

Example:

// Program to calculate the sum of array elements by passing to a function 

#include <stdio.h>
float calculateSum(float num[]);

int main() {
  float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};

  // num array is passed to calculateSum()
  result = calculateSum(num); 
  printf("Result = %.2f", result);
  return 0;
}

float calculateSum(float num[]) {
  float sum = 0.0;

  for (int i = 0; i < 6; ++i) {
    sum += num[i];
  }

  return sum;
}

Output :

Leave a Comment

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