Page Stats
Visitor: 549
C - Passing Array to Function
We can create functions that receives array as argument. To pass array in function, we need to write the array name in the function call.
There are 3 ways to declare function that receives array as argument.
- First way:
- Second way:
- Third way:
return_type function_name(datatype arrayname[]); Declaring blank subscript notation [] is the widely used technique.
return_type function_name(datatype arrayname[SIZE]); We can define size in subscript notation [].
return_type function_name(datatype *arrayname); You can also use the concept of pointer. In pointer chapter, we will learn about it.
Example 1: Passing array to function.
int minarray(int arr[], int size) { int min=arr[0], 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(); }
Minimum number is 3
Example 2: WAP for passing Array Elements to function argument.
void display(int n); void main() { int i; int a[] = {10, 20, 30, 40, 50}; clrscr(); for(i=0; i<5; i++) { display(a[i]); } getch(); } void display(int n) { printf(" %d ", n); }
10 20 30 40 50
Example 3: WAP for passing 2D Array to function argument.
Example 4: WAP for passing string to function argument.
void display(char []); void main() { char s[]="Programming"; clrscr(); display(s); getch(); } void display(char str[]) { puts(str); }
Programming
Example 5: WAP for passing array of string to function argument.
void display(char [][10]); void main() { char s[][10] = {"C", "C++", "Java", "Python", "PHP"}; clrscr(); display(s); getch(); } void display(char str[][10]) { int i; printf("Popular Computer Languages are:"); for(i=0;i<4;i++) { puts(str[i]); } }
Popular Computer Languages are:
C
C++
Java
Python
PHP
C
C++
Java
Python
PHP
Exercise on Array to function
- WAP to return array using function.
- WAP to find length of string using function (passing string).