How to Find All Indexes of an Element in an Array in C++?
In C++, an array is a collection of elements of the same type placed in contiguous memory locations. In this article, we will learn how to find all indexes of a specific element in an array in C++.
Example:
Input:
myArray = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
target = 3
Output:
The element 3 occurred at indices: 3 4 5
Finding All Indexes of an Element in an Array in C++
To find all indexes of an element in an array in C++, we have to iterate through the whole array looking for the target. If the target is found, we will print it. Otherwise, we can continue to the next loop.
C++ Program To Find All Indexes of an Element in an Array
The below example demonstrates how we can find all indexes of an element in an array in C++.
// C++ Program to illustrate how to find all indexes of a
// specific element in an array
#include <iostream>
using namespace std;
int main()
{
// Initializing an array with multiple occurrences of
// some elements
int myArray[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
int n = sizeof(myArray) / sizeof(myArray[0]);
// element to find
int target = 3;
cout << "The element " << target
<< " occurred at indices: ";
// Iterate through the array
for (int index = 0; index < n; ++index) {
if (myArray[index] == target) {
// If the element matches the search element,
// print the index
cout << index << " ";
}
}
return 0;
}
Output
The element 3 occurred at indices: 3 4 5
Time Complexity: O(n), here n is the size of the array.
Auxilliary Space: O(1)
Contact Us