Passing 1d2d Array in Functions
Passing 1d2d Array in Functions
Prepared by
Mrs. Preethy Jemima P
Assistant Professor
Department of CSE
SRM IST
Ramapuram Campus
Actual and Formal arguments in C
Arguments which are mentioned in the function call is known as the actual argument.
For example:
func1(12, 23);
here 12 and 23 are actual arguments.
Actual arguments can be constant, variables, expressions etc.
12
Formal Arguments
Arguments which are mentioned in the definition of the function is called formal arguments. Formal arguments are very similar to local variables inside the function. Just like local variables, formal
arguments are destroyed when the function ends.
EG: void add(int n) //n is a formal argument in this fn
Note:
• A one dimensional array can be easily passed
as a pointer, but syntax for passing a 2D array
to a function can be difficult to remember.
• One important thing for passing
multidimensional arrays is, first array
dimension does not have to be specified.
• The second (and any subsequent) dimensions
must be given.
• Eg: void add(int a[][2])
Formal and Actual Parameters One-
Dimensional Array
Actual Parameters:
int a[10];
Function call: add(a);
here,
a is the base address of the array add is the
function
Passing Single element
Example int a[5]={0,1,2,3,4};
Function call: add(a[1]);
Here,
add is the function name,
a[1] is the second element of the array,
value 1 is passed to the array.
Adding Constant five to the given array using
functions(One-Dimensional)
int main()
{ int a[50],i,n;
printf(“Enter the no of elts”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
scanf(“%d”,&a[i]);
add(a,n);
for(i=1;i<=n;i++)
printf(“Answer %d\n”,a[i]);
return 0; }
void add(int a[],int n)
{ int r;
for(r=1;r<=n;r++)
{ a[r]=a[r]+5; }
Output
Input:
Enter the no of elts : 5
2
4
6
8
10
Answer 7 9 11 13 15
2D Array –passing in function
int main()
{
int num[2][2], i, j;
printf("Enter 4 numbers:\n");
for (i = 0; i < 2; ++i)
{ for (j = 0; j < 2; ++j)
{ scanf("%d", &num[i][j]);
} } // passing multi-dimensional array to displayNumbers function
displayNumbers(num);
return 0; }
void displayNumbers(int num[2][2])
{int i, j;
printf("Displaying:\n");
for (i = 0; i < 2; ++i)
{ for (j = 0; j < 2; ++j)
{ printf("%d\n", num[i][j]);
}}
} // void displayNumbers(int num[][2]) is also valid