To get the index of a specified element in an array in C, you can iterate through the array and compare each element with the specified element.
In this example,
arr
with values 10, 20, 30, 40, 50.#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int specifiedElement = 30;
int size = sizeof(arr) / sizeof(arr[0]);
int index = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == specifiedElement) {
index = i;
break;
}
}
if (index != -1) {
printf("Index of specified element %d is: %d\n", specifiedElement, index);
} else {
printf("Specified element not found in the array\n");
}
return 0;
}
Index of specified element 30 is: 2
In this example,
arr
with values 10, 20, 30, 40, 50.#include <stdio.h>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int specifiedElement = 60;
int size = sizeof(arr) / sizeof(arr[0]);
int index = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == specifiedElement) {
index = i;
break;
}
}
if (index != -1) {
printf("Index of specified element %d is: %d\n", specifiedElement, index);
} else {
printf("Specified element not found in the array\n");
}
return 0;
}
Specified element not found in the array
In this tutorial, we learned How to get the Index of Specified Element in an Array in C language with well detailed examples.