Passing Array to function

There are various general problems which require passing more than one variable of the same type to a function. Array are defined as the formal parameter will automatically refer to the array specified by the array name defined as an actual parameter.

syntax to pass an array to the function

functionname(arrayname);

Methods to declare a function that receives an array as an argument

There are three ways to declare the function that receives an array as an argument.

  • return_type function(type arrayname[])
  • return_type function(type arrayname[SIZE])
  • return_type function(type*arrayname)

Let’s see the example of passing array to function

#include<stdio.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];    
}    
}    
return min;    
}   
    
int main(){      
int i=0,min=0;    
int numbers[]={4,5,7,3,8,9};   
min=minarray(numbers,6);   
printf("minimum number is %d \n",min);    
return 0;  
}

Output

minimum number is 3

Returning array to function

Function cannot return more than one value.Returning array is similar to passing the array into the function.The name of the array is returned from the function.

Syntax for Function returning an array

int * Function_name() {
//some statements;
return array_type;
}

Consider the following example that contains a function returning the sorted array

#include<stdio.h>   
int* Bubble_Sort(int[]);  
void main ()    
{    
    int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};     
    int *p = Bubble_Sort(arr), i;  
    printf("printing sorted elements ...\n");  
    for(i=0;i<10;i++)  
    {  
        printf("%d\n",*(p+i));  
    }  
}    
int* Bubble_Sort(int a[])    
{  
int i, j,temp;     
    for(i = 0; i<10; i++)    
    {    
        for(j = i+1; j<10; j++)    
        {    
            if(a[j] < a[i])    
            {    
                temp = a[i];    
                a[i] = a[j];    
                a[j] = temp;     
            }     
        }     
    }     
    return a;  
}

Output

Printing Sorted Element List ...
7  
9   
10  
12  
23 
23  
34  
44  
78  
101

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews