C Programming

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 :

Premium E-Books & Study Materials.

Access university-specific notes and programming guides. Download instantly to start studying.

Share Article :

TopperWorld
Prime E-Books

Master programming and core CS concepts with expert-curated study guides.

Recent Tutorials :

What Jobs Will AI Replace: Which Careers Will Grow in the Next 5 Years?
Java Most Asked Interview Question and Answer
Top 10 AI companies in India
How Generative AI is Transforming Programming
Top GITHUB Interview Questions and Answers