C – Find Index of Specific Element
To find the index of specified element in given Array in C programming, iterate over the elements of array, and during each iteration check if this element is equal to the element we are searching for. If the array element equals the specified element, stop searching further and the index during that iteration is the required index.
Examples
In the following example, we take an integer array arr
, and find the index of the element x = 8
in this array.
We use C For Loop to iterate over the elements of array, and sizeof operator to get the length of array.
main.c
</>
Copy
#include <stdio.h>
int main() {
int arr[] = {2, 4, 6, 8, 10};
int x = 8;
int arrLen = sizeof arr / sizeof arr[0];
int index = -1;
for (int i = 0; i < arrLen; i++) {
if (arr[i] == x) {
index = i;
break;
}
}
if (index > -1) {
printf("Index : %d\n", index);
} else {
printf("%d is not present in this array.\n", x);
}
return 0;
}
Output
Index : 3
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to find the index of a specific element in given Array, with examples.