Linear Searech

Hello, I have a problem with this search.I know what the algoritm must do, but when I enter a number above 10 it says the number is in the array but that is not in the array and I don't know how to make it work.


#include <iostream>

using namespace std;


int linear_search(int *a,int n,int x)
{
int i;
for(i = 0; i < n; ++i){
if(x == *(a+i)
{
return i;
}
}
return -1;
}
int main()
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
int x,i;
int n = sizeof(a);

cout << "Enter the number that must be searched:" << endl;
cin >> x;

int result = linear_search(a,n,x);
if(result >= 0)
{
std::cout<<"The number "<<a[result]<<"======was found @ =====" <<result<< " index "<<endl;
}
else{cout << "Number not found in array!!! " << endl;}

return 0;


}
1. Please edit your code and use code tags - http://www.cplusplus.com/articles/jEywvCM9/

2. It doesnt compile, you're missing a parenthesis - (x == *(a+i) // add a )

3. You can improve the function by making it a boolean. Let it return true if it is in the array, and false if it is not.

4. Just write a[i] instead of *(a + i)

Edit:

5. Read post under me.
Last edited on
The problem is this:
int n = sizeof(a);
This sets n to the number of bytes in array a, not the number of entries in the array. Since each int typically takes 4 bytes, this is probably setting n to 40 instead of 10. That means causes linear_search() to look for array entries that don't exist and when that happens, you get undefined behavior, which means anything can happen.

The recommended way to fix this is to use std::array instead of raw arrays. But if you want to use arrays, try this:
int n = sizeof(a) / sizeof(a[0]);
This divides the total size of the array by the size of the first element, resulting in the number of elements in the array.
I find your lack of formatting very disturbing...

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
39
#include <iostream>

using namespace std;

int linear_search(int *a,int n,int x)
{
	int i;
	for(i = 0; i < n; ++i)
	{
		if(x == *(a+i)	// syntax error for sure
				// try: if(x == *(a+i))
		{
			return i;
		}
	}
	
	return -1;
}
	
int main()
{
	int a[] = {1,2,3,4,5,6,7,8,9,10};
	int x,i;
	int n = sizeof(a);	// n != 10, n == 10 * sizeof int
				// try int n = sizeof(a) / sizeof(a[0]);
	cout << "Enter the number that must be searched:" << endl;
	cin >> x;
	int result = linear_search(a,n,x);
	if(result >= 0)
	{
		std::cout<<"The number "<<a[result]<<"======was found @ =====" <<result<< " index "<<endl;
	}
	else
	{
		cout << "Number not found in array!!! " << endl;
	}

	return 0;
}
Thanks now it is working ! And sorry I forgot to format the code.
Topic archived. No new replies allowed.