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;
}
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;
}
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;
}
#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;
}