In C, there are various general problems which requires passing more than one variable of the same type to a function.
Declaring Function with array as a parameter
There are two possible ways to do:
- Have an array as a parameter.
int sum (int arr[ ]);
- Or, have a pointer to hold the base address
of array.
int sum (int* a);
When a formal parameter is declared is declared in a function as an array, it is interpreted as a pointer variable not as an array.
Passing arrays as parameter to function
#include<stdio.h>
{
int
myArray[] = { 2, 3, 4 };
printArray(myArray[2]); //Passing array element myArray[2]
only.
return
0;
}
{
printf("%d", a);
}
Example:
{
float
avg;
int
marks[] = {99, 90, 96, 93, 95};
avg =
findAverage(marks); // name of the
array is passed as argument.
printf("Average marks = %.1f", avg);
}
float findAverage(int marks[])
{
int i,
sum = 0;
float
avg;
for (i
= 0; i <= 4; i++)
{
sum
+= marks[i];
}
avg =
(sum / 5);
return
avg;
}
Example:
{
int
arr[3][3], i, j;
printf("Please enter 9 numbers for the array: \n");
for (i
= 0; i < 3; ++i)
{
for
(j = 0; j < 3; ++j)
{
scanf("%d", &arr[i][j]);
}
}
//
passing the array as argument
displayArray(arr);
return
0;
}
{
int i,
j;
printf("The complete array is: \n");
for (i
= 0; i < 3; ++i)
{
//
getting cursor to new line
printf("\n");
for
(j = 0; j < 3; ++j)
{
// \t is used to provide tab space
printf("%d\t", arr[i][j]);
}
}
No comments:
Post a Comment