write a program to find out whether data entered by user is present in
one dimensional array of following 10 elements, using linear search.
1, 5, 21, 16, 49, 35, 87, 63, 90, 6
#include<iostream>
#include<conio.h>
usingnamespace std;
int main()
{
int a[10], n, x, i, flag = 0;
int a[i] = {1, 2, 3, 4, 5, 6, 7 ,8, 9. 10};
cout << "\nEnter Element to search:";
cin >> x;
for (i = 0;i < n;++i)
{
if (a[i] == x)
{
flag = 1;
break;
}
}
if (flag)
cout << "\nElement is Found at position " << i + 1;
else
cout << "\nElement not found";
return 0;
}
but this code doesn't work and i get errors
I am using MinGW GCC compiler of Quincy 2005
can someone tell me where i am wrong
one of which has 10 elements and the other has undefined number of elements because variable i 1) is not a const expression and 2) was not initialized.
#include<iostream>
#include<conio.h>
usingnamespace std;
int main()
{
int n, x, i, flag = 0;
int a[10] = {1, 2, 3, 4, 5, 6, 7 ,8, 9. 10};//or int a[i] ={10 elements};
cout << "\nEnter Element to search:";
cin >> x;
for (i = 0;i < n;i++)
{
if (a[i] == x)
{
flag = 1;
break;
}
}
if (flag)
cout << "\nElement is Found at position " << i + 1;
else
cout << "\nElement not found";
return 0;
}
however it still shows errors
i would paste errors here but my ide Quincy 2005 does not let me copy
some of them are:
"type conservation << before token
invalid constructor and destructor expected
extra ;"
i want to know is my linear search algorithm ok would it work?
please help
parjanya
It is the common approach to return an index or a pointer to an element beyond the array if the target element was not found. Also you should not declare variables before their usage. So I would rewrite your code the following way
#include<iostream>
usingnamespace std;
int main()
{
constint N = 10;
int a[N] = { 1, 5, 21, 16, 49, 35, 87, 63, 90, 6 };
cout << "\nEnter Element to search: ";
int x = 0;
cin >> x;
int i = 0;
while ( ( i < N ) && !( a[i] == x ) ) ++i;
if ( i != N )
cout << "\nElement is Found at position " << i + 1;
else
cout << "\nElement not found";
return 0;
}
There is standard algorithm std::find that does all the work in you program. With its using the program could be rewritten as
#include<iostream>
#include <algorithm>
#include <iterator>
usingnamespace std;
int main()
{
constint N = 10;
int a[N] = { 1, 5, 21, 16, 49, 35, 87, 63, 90, 6 };
cout << "\nEnter Element to search: ";
int x = 0;
cin >> x;
int *p = find( a, a + N, x );
if ( p != a + N )
cout << "\nElement is Found at position " << distance( a, p ) + 1;
else
cout << "\nElement not found";
return 0;
}