C++ Program to Find Index of First Occurrence of a Value in Array
Last Updated :
11 Mar, 2024
Improve
In C++, an array is a data structure that stores elements of the same type in contiguous memory locations. In this article, we will learn how to find the index of the first occurrence of a specific value in an array in C++.
Example:
Input:
int arr[] = {5, 7, 1, 2, 3, 7, 1}
Target = 1
Output:
The first occurrence of 1 is at index: 2
Finding the Index of the First Occurrence of an Element in an Array
To find the index of the first occurrence of a value in an array, we can simply use a loop to iterate through the array and check if the element matches with the target if it matches return the index that is the first occurrence of a value in an array.
C++ Program to Find the Index of the First Occurrence of a Value in an Array
The below example demonstrates the use of a for loop to find the index of the first occurrence of a value in a given array in C++.
// C++ Program to show how to Find the Index of the First Occurrence of
// a Value in an Array
#include <iostream>
using namespace std;
int main()
{
// initializing array
int arr[] = { 5, 7, 1, 2, 3, 7, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
// target whose first occurence need to be searched
int target = 1;
int index = -1;
// using a for loop to find the first occurrence of
// the element in the array.
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
index = i;
break;
}
}
// if target is found print it's index
if (index != -1) {
cout << "The first occurrence of " << target
<< " is at index: " << index << endl;
}
// else element not found
else {
cout << "Element not found." << endl;
}
return 0;
}
Output
The first occurrence of 1 is at index: 2
Time Complexity: O(N), here N is the number of elements in the array.
Auxiliary Space: O(1)