Pass an array by value in C

C++ProgrammingServer Side Programming

Here is an example of passing array by value in C language,

Example

 Live Demo

#include <stdio.h>
float avg(float a[]) {
   int i;
   float avg, sum = 0.0;

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

   return avg;
}
int main() {
   float avg1, a[] = {63,21,34.4,12.5,3,2.2};
   avg1 = avg(a);
   printf("Average : %f", avg1);
   return 0;
}

Output

Here is the output

Average : 22.683332

In the above program, The actual code of calculating average is present in avg() function. In the for loop, the sum of array elements and average are calculated.

float avg(float a[]) {
   int i;
   float avg, sum = 0.0;

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

   return avg;
}

In the main() function, the values are passed to the array and the function avg() is called.

float avg1, a[] = {63,21,34.4,12.5,3,2.2};
avg1 = avg(a);
raja
Published on 23-Oct-2018 13:50:26
Advertisements