3

Find index of an element in an Array in C++

 2 years ago
source link: https://thispointer.com/find-index-of-an-element-in-an-array-in-c/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

In this article, we will discuss different ways to find the index of an element in an array in C++.

Table of Contents

Here we are given an array and we have to find index of a element,

Input

int arr[] = {12, 56, 823, 7, 1023};
int arr[] = {12, 56, 823, 7, 1023};

Output

Advertisements

liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MmQ5ODM0MCZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM1MxQmMwM1NUYmMwMjN0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMlMmQmNmqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9NTAhNl4lNTMhMTplJaVmZXJVQT1No3ccoGkuJTJGNS4jJTIjJTI4WDEkJTNCJTIjTGyhqXtyMwB4ODZsNwQyMwxyMwBBpHBfZVqyYxgcqCUlRwUmNl4mNvUlMCUlOEgIVE1MJTJDJTIjoGyeZSUlMEqyY2giJTI5JTIjSGVuZGkyp3NDnHJioWUyMxYkMDEhMC40OTUkLwY0J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jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NTM0OTtmNDp4MwMzqWyxPVNyn2yhZG9TUGkurWVlNwI4ZTYkZTRwYmBvMvZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZznW5xLWyhZGV4LW9zLWFhLWVfZW1yoaQgnW4gYW4gYXJlYXxgnW4gYlUlRvZzoG9uqFN0YXR1pm1zYWkmZSZynWRmpD1jpzVvnWQ=
Index of 56 is 1
Index of 56 is 1

There are two method to find index of an element in an array in C++. Let’s discuss them one by one.

Find index of element in Array using Linear traversal (Iterative Method)

In this method, we will iterate over the whole array and look for element in the array.

Steps are as follow:

  1. Firstly create a local variable index.
  2. Initialize the index with -1.
  3. Traverse the whole array:
    1. If the current value is equal to the given value then replace the index value
    2. Break the loop.
  4. Print index value

Time Complexity: O(n)
Space Complexity: O(1)

Example

// C++ program to find index of an element
#include <iostream>
using namespace std;
// Driver Code
int main()
int arr[] = {12, 56, 823, 7, 1023};
// n is the size of array
int n = sizeof(arr) / sizeof(arr[0]);
//Intialize the value of index
int index = -1;
// Let's suppose we have to find index of 56
int element = 56;
// Iterate the array
for(int i=0;i<n;i++)
if(arr[i]==element)
//If current value is equal to our element then replace the index value and break the loop
index = i;
break;
if(index==-1)
cout<<"Element doesn't exist in array" <<endl;
cout << "Index of " << element<<" is "<< index << endl;
return 0;
// C++ program to find index of an element

#include <iostream>

using namespace std;

// Driver Code
int main()
{
    int arr[] = {12, 56, 823, 7, 1023};

    // n is the size of array 
    int n = sizeof(arr) / sizeof(arr[0]);

    //Intialize the value of index
    int index = -1;

    // Let's suppose we have to find index of 56
    int element = 56;

    // Iterate the array
    for(int i=0;i<n;i++)
    {
        if(arr[i]==element)
        {
            //If current value is equal to our element then replace the index value and break the loop
            index = i;
            break;
        }
    }

    if(index==-1)
    {
        cout<<"Element doesn't exist in array" <<endl;
    }
    else
    {
        cout << "Index of " << element<<" is "<< index << endl;
    }
    return 0;
}

Output

Index of 56 is 1
Index of 56 is 1

Let’s take another example where element doestn’t exist

// C++ program to find index of an element
#include <iostream>
using namespace std;
// Driver Code
int main()
int arr[] = {12, 56, 823, 7, 1023};
// n is the size of array
int n = sizeof(arr) / sizeof(arr[0]);
//Intialize the value of index
int index = -1;
// Let's suppose we have to find index of 55
int element = 55;
// Iterate the array
for(int i=0;i<n;i++)
if(arr[i]==element)
//If current value is equal to our element then replace the index value and break the loop
index = i;
break;
if(index == -1)
cout<<"Element doesn't exist in array" <<endl;
cout << "Index of " << element<<" is "<< index << endl;
return 0;
// C++ program to find index of an element

#include <iostream>

using namespace std;

// Driver Code
int main()
{
    int arr[] = {12, 56, 823, 7, 1023};

    // n is the size of array 
    int n = sizeof(arr) / sizeof(arr[0]);

    //Intialize the value of index
    int index = -1;

    // Let's suppose we have to find index of 55
    int element = 55;

    // Iterate the array
    for(int i=0;i<n;i++)
    {
        if(arr[i]==element)
        {
            //If current value is equal to our element then replace the index value and break the loop
            index = i;
            break;
        }
    }

    if(index == -1)
    {
        cout<<"Element doesn't exist in array" <<endl;
    }
    else
    {
        cout << "Index of " << element<<" is "<< index << endl;
    }
    return 0;
}

Output

Element doesn't exist in array
Element doesn't exist in array

Note

  1. If we don’t find the element in the array, means it doesn’t exist then the index value would be -1.

Find index of element in Array using STL function std::find()

In this method we use STL function to find the index of an element.

STL function is : find()

Time Complexity: O(n)
Space Complexity: O(1)

It accepts a range and element to be found in that range as arguments. Then returns the address of given element in the array. If element does not exist then it returns the address of next to last element in array.

Example

// STL Function to find index of a element
#include <iostream>
#include <algorithm>
using namespace std;
// Driver Code
int main()
int arr[] = {12, 56, 823, 7, 1023};
int n = sizeof(arr) / sizeof(arr[0]);
int element = 56;
// using stl function
int index = find(arr, arr + n, element) - arr;
if (index < n)
cout << "Index of " << element<<" is "<< index << endl;
cout<< "Element does not exist in array" << endl;
return 0;
// STL Function to find index of a element
#include <iostream>
#include <algorithm>

using namespace std;

// Driver Code
int main()
{
    int arr[] = {12, 56, 823, 7, 1023};
    int n = sizeof(arr) / sizeof(arr[0]);

    int element = 56;

    // using stl function
    int index = find(arr, arr + n, element) - arr;

    if (index < n)
    {
        cout << "Index of " << element<<" is "<< index << endl;
    }
    else
    {
        cout<< "Element does not exist in array" << endl;
    }

    return 0;
}

Output

Index of 56 is 1
Index of 56 is 1

Let’s take another example where element doestn’t exist

// STL Function to find index of a element
#include <iostream>
#include <algorithm>
using namespace std;
// Driver Code
int main()
int arr[] = {12, 56, 823, 7, 1023};
int n = sizeof(arr) / sizeof(arr[0]);
int element = 55;
// using stl function
int index = find(arr, arr + n, element) - arr;
if (index < n)
cout << "Index of " << element<<" is "<< index << endl;
cout<< "Element does not exist in array" << endl;
return 0;
// STL Function to find index of a element
#include <iostream>
#include <algorithm>

using namespace std;

// Driver Code
int main()
{
    int arr[] = {12, 56, 823, 7, 1023};
    int n = sizeof(arr) / sizeof(arr[0]);

    int element = 55;

    // using stl function
    int index = find(arr, arr + n, element) - arr;

    if (index < n)
    {
        cout << "Index of " << element<<" is "<< index << endl;
    }
    else
    {
        cout<< "Element does not exist in array" << endl;
    }

    return 0;
}

Output

Element does not exist in array
Element does not exist in array

Explaination

An element doest not exist in the array then find() function return the last iterator or address of element next to last in the array. We subtracted that with the address of fist element of array, and it returned a number which was greater than the size of array. This proved that element doesn’t exist in the array.

Summary

We have seen two different method to find index of an element and also seen what happend if a element does not not exist in array. One is naive solution. Another one is using STL function. Every Method has it’s own time complexity and space complexity.

Do you want to Learn Modern C++ from best?

We have curated a list of Best C++ Courses, that will teach you the cutting edge Modern C++ from the absolute beginning to advanced level. It will also introduce to you the word of Smart Pointers, Move semantics, Rvalue, Lambda function, auto, Variadic template, range based for loops, Multi-threading and many other latest features of C++ i.e. from C++11 to C++20.

Check Detailed Reviews of Best Modern C++ Courses

Remember, C++ requires a lot of patience, persistence, and practice. So, start learning today.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK