Search for Multiple Occurrences of an Element in an Array
To search for multiple occurrences of an element in an array in C, we can iterate through the array using a loop and check each element against the target value. If a match is found, we store or display its index. This method ensures that we can find and track all occurrences of the given element efficiently.
Examples to Search for Multiple Occurrences
1. Searching for Multiple Occurrences Using a for
Loop
In this example, we will iterate through an integer array using a for
loop and search for a target number. We will print all indices where the number appears.
main.c
</>
Copy
#include <stdio.h>
int main() {
int arr[] = {4, 7, 2, 7, 8, 7, 1, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 7;
printf("Occurrences of %d found at indices: ", target);
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
printf("%d ", i);
}
}
return 0;
}
Explanation:
- We declare an integer array
arr[]
with multiple occurrences of7
. - We calculate the size of the array using
sizeof(arr) / sizeof(arr[0])
. - We define the
target
variable, which holds the number we are searching for. - We iterate through the array using a
for
loop. - Inside the loop, we check if
arr[i] == target
. - If a match is found, we print the index
i
.
Output:
Occurrences of 7 found at indices: 1 3 5 7
2. Storing Indices of All Occurrences in an Array
In this example, we will store all indices where the target value appears in a separate array and display them at the end.
main.c
</>
Copy
#include <stdio.h>
int main() {
int arr[] = {3, 5, 3, 9, 3, 10, 3};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int indices[size];
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
indices[count] = i;
count++;
}
}
printf("Total occurrences of %d: %d\nIndices: ", target, count);
for (int i = 0; i < count; i++) {
printf("%d ", indices[i]);
}
return 0;
}
Explanation:
- We declare an integer array
arr[]
with multiple occurrences of3
. - We calculate the size of the array using
sizeof(arr) / sizeof(arr[0])
. - We define the
target
variable to hold the number we are searching for. - We declare an array
indices[]
to store the indices wheretarget
is found. - The
count
variable keeps track of the number of occurrences. - We iterate through the array using a
for
loop. - If a match is found, we store the index in
indices[count]
and incrementcount
. - After the loop, we print the total count and display all stored indices.
Output:
Total occurrences of 3: 4
Indices: 0 2 4 6
Conclusion
In this tutorial, we explored how to search for multiple occurrences of an element in an array in C. We covered:
- Using a
for
loop: To search and print indices directly. - Storing indices in an array: To keep track of occurrences and print them later.