-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathLinearSearch.cpp
More file actions
38 lines (34 loc) · 807 Bytes
/
LinearSearch.cpp
File metadata and controls
38 lines (34 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// C++ code to linearly search x in arr[].
//If element is present then return its location, otherwise return -1
#include <iostream>
using namespace std;
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
int main()
{
int n,x;
cout<<"Enter number of elements in array: ";
cin>>n;
int arr[n];
cout<<"\nEnter array elements: ";
for(int i=0;i<n;i++){
cin>>arr[i];
}
cout<<"\nEnter element to be searched: ";
cin>>x;
int result = search(arr, n, x);
if(result==-1){
cout<<"Element is not present in array";
}
else{
cout<<"Element is present at index "<<result;
}
return 0;
}