Array to Function in C

Passing Array to Function in C

  • To reuse the array operation, we can create functions that receives array as argument. To pass array in function, we need to write the array name only in the function call.
Passing array to Function

functionname(arrayname);//passing array 

There are 3 ways to declare function that receives array as argument.
First way:
return_type function(type arrayname[]) 
Declaring blank subscript notation [] is the widely used technique.
Second way:
return_type function(type arrayname[SIZE])  
Optionally, we can define size in subscript notation [].

Third way:
return_type function(type *arrayname)  

C language passing array to function example

#include <stdio.h>    
#include <conio.h>    
int minarray(int arr[],int size){  
int min=arr[0];  
int i=0;  
for(i=1;i<size;i++){  
if(min>arr[i]){  
min=arr[i];  
}  
}//end of for  
return min;  
}//end of function  
  
void main(){    
int i=0,min=0;  
int numbers[]={4,5,7,3,8,9};//declaration of array  
clrscr();    
  
min=minarray(numbers,6);//passing array with size  
printf("minimum number is %d \n",min);  
  
getch();    
}    
Output
minimum number is 3

Example

#include <stdio.h>
void display(int age1, int age2)
{
    printf("%d\n", age1);
    printf("%d\n", age2);
}
int main()
{
    int ageArray[] = {2, 9, 5, 12};
    // Passing second and third elements to display()
    display(ageArray[1], ageArray[2]); 
    return 0;

}
Output
9
5

Example

// Program to calculate the sum of array elements by passing to a function 
#include <stdio.h>
float calculateSum(float age[]);
int main() {
    float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
    // age array is passed to calculateSum()
    result = calculateSum(age); 
    printf("Result = %.2f", result);
    return 0;
}
float calculateSum(float age[]) {
  float sum = 0.0;
  for (int i = 0; i < 6; ++i) {
sum += age[i];
  }
  return sum;

}

Expected Output

Result = 162.50

Post a Comment

Previous Post Next Post