In this blog, we will create a program to find an index of an element by element value.
Index of an element?
Lists are an ordered collection of items, each element has its own unique position, and each element can be accessed by telling Python the position. These positions are called indexes.
Algorithm to find an index of an element
- First, create the index of the local variable.
- Initialize the index with -1.
- Go through the entire field:
- If the current value is equal to the given value, replace the index value.
- Break the loop.
- Print the index value
C++ code to find an index of an element
// 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; }
The output of the above code
Let’s take another example where an element doesn’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; } else { cout << "Index of " << element<<" is "<< index << endl; } return 0; }
The output of the above code
Explanation of the code
If the element in the array does not exist, then the find() function returns the last iterator or the address of the element next to the last in the array. We subtracted it with the address of the array’s first element and returned a number greater than the array’s size. This proved that the element did not exist in the array.