Passing Array to Function in C
C Program to pass array to function
We will write a program for passing array to function in C language. This will help to understand the basic structure of programming. In this program, we will learn how to pass simple and multi-dimensional arrays to function with examples.
Pass Individual Array Elements :
In the program, we will learn how to pass individual array elements to a function.
We have created a display function which takes two array elements as arguments.
Example
#include<stdio.h>
void display(int age1, int age2) {
printf("%d\n", age1);
printf("%d\n", age2);
}
int main() {
int ageArray[] = {2, 8, 4, 12};
display(ageArray[1], ageArray[2]);
return 0;
}
Output
8 4
Pass Arrays to Functions :
In the program, we will learn how to pass the whole array to function in C.
We have created a calculateSum function which takes a whole array as argument.
Example
#include<stdio.h>
float calculateSum(float num[]);
int main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
Output
Result = 162.50
Pass Multi-dimensional Arrays to Functions :
In the program, we will learn how to pass a multi-dimensional array to function in C.
We have created a function named displayNumbers which takes a 2-D array as its argument.
Example
#include<stdio.h>
void displayNumbers(int num[2][2]);
int main() {
int num[2][2];
printf("Enter 4 numbers:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
scanf("%d", &num[i][j]);
}
}
displayNumbers(num);
return 0;
}
void displayNumbers(int num[2][2]) {
printf("Displaying:\n");
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
printf("%d\n", num[i][j]);
}
}
}
Output
Enter 4 numbers: 2 3 4 5 Displaying: 2 3 4 5
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Login/Signup to comment