Skip to content

Commit 93097a5

Browse files
authored
Update LinearSearch.cpp
1 parent 445b168 commit 93097a5

File tree

1 file changed

+29
-26
lines changed

1 file changed

+29
-26
lines changed
Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,33 @@
1-
// C++ code to linearly search x in arr[]. If x
2-
// is present then return its location, otherwise
3-
// return -1
4-
5-
#include <iostream>
6-
using namespace std;
1+
#include<iostream>
72

8-
int search(int arr[], int n, int x)
9-
{
10-
int i;
11-
for (i = 0; i < n; i++)
12-
if (arr[i] == x)
13-
return i;
14-
return -1;
15-
}
3+
using namespace std;
164

17-
// Driver code
18-
int main(void)
5+
int main()
196
{
20-
int arr[] = { 2, 3, 4, 10, 40 };
21-
int x = 10;
22-
int n = sizeof(arr) / sizeof(arr[0]);
23-
24-
// Function call
25-
int result = search(arr, n, x);
26-
(result == -1)
27-
? cout << "Element is not present in array"
28-
: cout << "Element is present at index " << result;
29-
return 0;
7+
int a[20],n,x,i,flag=0;
8+
cout<<"How many elements?";
9+
cin>>n;
10+
cout<<"\nEnter elements of the array\n";
11+
12+
for(i=0;i<n;++i)
13+
cin>>a[i];
14+
15+
cout<<"\nEnter element to search:";
16+
cin>>x;
17+
18+
for(i=0;i<n;++i)
19+
{
20+
if(a[i]==x)
21+
{
22+
flag=1;
23+
break;
24+
}
25+
}
26+
27+
if(flag)
28+
cout<<"\nElement is found at position "<<i+1;
29+
else
30+
cout<<"\nElement not found";
31+
32+
return 0;
3033
}

0 commit comments

Comments
 (0)