Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to pass individual elements in an array as argument to function in C language?
In C programming, you can pass individual array elements as arguments to functions by specifying the array element with its index in the function call. The function receives these elements as separate parameters, not as an array.
Syntax
functionName(array[index1], array[index2], ...);
Example 1: Passing First and Last Elements
This example demonstrates how to pass the first and last elements of an array to a function −
#include <stdio.h>
void display(int first, int last) {
printf("First element = %d
", first);
printf("Last element = %d
", last);
}
int main() {
int a[5], i;
printf("Enter 5 elements: ");
for (i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
display(a[0], a[4]); // passing individual elements
return 0;
}
Enter 5 elements: 10 20 30 40 50 First element = 10 Last element = 50
Example 2: Passing Multiple Individual Elements
Here's another example showing how to pass specific array elements to a function −
#include <stdio.h>
void arguments(int a, int b) {
printf("First element = %d
", a);
printf("Sixth element = %d
", b);
}
int main() {
int a[10], i;
printf("Enter 6 elements:
");
for (i = 0; i < 6; i++) {
scanf("%d", &a[i]);
}
arguments(a[0], a[5]); // passing first and sixth elements
return 0;
}
Enter 6 elements: 1 2 3 4 5 6 First element = 1 Sixth element = 6
Key Points
- Individual array elements are passed by value, meaning the function receives copies of the values.
- Changes made to parameters inside the function do not affect the original array elements.
- You can pass any number of individual elements as separate arguments to a function.
- Each array element is treated as a regular variable when passed individually.
Conclusion
Passing individual array elements to functions in C is straightforward − simply specify the array element with its index in the function call. This approach is useful when you need to process specific elements rather than the entire array.
Advertisements
