Passing single dimension array to function
A single array (or) entire array can be passed to a function. Both one dimensional array (or) two dimensional (or) multidimensional array can be passed to a function as argument.
1. Passing entire array to function : To pass an entire array to a function, The array name must appear by itself without braces (or) subscripts as an actual arguments with in the function call. whereas formal parameters should be represented as a array variables. In function prototype, array arguments are represented as empty pair of braces.
syntax: function_prototype(data_type []);
calling function(arrayname);
called_function(data_type arrayname[])
Example program for passing entire array to function:
void action(int []);
main()
{
int i, a[10];
clrscr();
printf("\n Enter 5 array elements");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
action(a);
getch();
}
void action(int a[])
{
int i;
for(i=0;i<5;i++)
printf("%d",a[i]);
}
2. Passing single array element to a function: In C-language the name of the array represents the address of its first element. By passing the array name, actually we are passing the address of the array to the called function.
syntax: function_prototype(data_type);
calling function(arrayname[]);
called_function(data_type arrayname)
Example program for passing single array element to a function:
void action(int);
main()
{
int i, a[5];
clrscr();
printf("\n Enter 5 array elements");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
action(a[2]);
getch();
}
void action(int a)
{
printf("%d",a);
}
No comments:
Post a Comment