Find a Fixed Point (Value equal to index) in a given array in C++ Program


In this tutorial, we are going to solve the following problem.

Given an array, find the number which is equal to the index. It's a straightforward problem.

Iterate over the given array and return the index which is equal to the array element.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int linearSearch(int arr[], int n) {
   for(int i = 0; i < n; i++) {
      if(arr[i] == i) {
         return i;
      }
   }
   return -1;
}
int main() {
   int arr[] = {10, 20, 30, 40, 50, 5, 60};
   cout << linearSearch(arr, 7) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

5

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 01-Feb-2021

197 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements