Open In App

How to Find the Index of an Element in an Array in C++?

Last Updated : 18 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is a data structure used to store similar types of data in contiguous memory locations. In this article, we will learn how to find the index of an element in an array in C++.

Example:

Input: 
myArray = {1, 2, 3, 4, 5};
target = 3

Output:
The element 3 is at index: 2

Finding the Index of an Element in C++ Array

To find the index of an element in an array in C++, we can use the find() function that performs the linear search in the given range and returns the pointer to the matching element. We can then find the index by subtracting the pointer to the beginning of the array from this pointer.

C++ Program to Find the Index of an Element in an Array

The following program illustrates how we can find the index of an element in an array in C++.

C++
// C++ Program to illustrate how to find the index of an
// element in an array
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    // Initializing an array
    int myArray[] = { 1, 2, 3, 4, 5 };
    int n = sizeof(myArray) / sizeof(myArray[0]);

    // element to find
    int target = 3;
    // using find() to get the pointer to the first
    // occurence
    int* targetPtr = find(&myArray[0], myArray + n, target);

    // getting index from pointer
    int targetIndex = targetPtr - myArray;

    // checking if the element found or not
    if (targetIndex > 4)
        cout << "Element not Found!\n";
    else
        cout << "Element Found at Index: " << targetIndex;

    return 0;
}

Output
Element Found at Index: 2

Time Complexity: O(n), here n is the size of the array. 
Auxiliary Space: O(1)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads