C++ Program to Find Index of First Occurrence of a Value in Array
Last Updated :
11 Mar, 2024
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++
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 5, 7, 1, 2, 3, 7, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
int target = 1;
int index = -1;
for ( int i = 0; i < n; i++) {
if (arr[i] == target) {
index = i;
break ;
}
}
if (index != -1) {
cout << "The first occurrence of " << target
<< " is at index: " << index << endl;
}
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)
Share your thoughts in the comments
Please Login to comment...