In this post, we will learn "How to search for an element in an array".
To search for an element in an array first you have to traverse through all the elements in the given array.
This method is known as Linear search.
The full code is given below:
C++ code to implement the linear search operation
Here x is the element you want to search in the given array and we will output the position of that element if it is present otherwise -1.
#include <iostream>
using namespace std;
//Function for linear search
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]); //way to find out how many elements are present in array
int result = search(arr, n, x); // Function call
(result == -1)
? cout << "-1";
: cout << "Element is present at index " << result;
return 0;
}
Try by yourself to do the above task without making a function and it should work as the image given below:
Comments
Post a Comment