Searching for an array

Hello programmers i need my code to do this for example "I will enter a number 2 the output should be number 8" and can someone turn it into a function thankyou

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
  #include<iostream>
using namespace std;

int linearSearch(int array[], int size,int searchKey){
  
for(int i=0; i<size;i++){
if(searchKey==array[i]){
return i;
}
}
return -1;

}

int main(){
	int const max=0;
	int a[]={9,6,8,90,56,78};
	int getSearchNumber,exme ; 
	cout<<"Enter a Number here"<<endl;
	cin>>getSearchNumber;

	int result = linearSearch(a,max,getSearchNumber);
	if(result>=0){
cout<<"The number "<<a[result]<<"was found"<<endl;

}else
cout<<"Nothing Found"<<endl;
system ("pause");
return 0;
}
Last edited on
Hi,

Firstly if you enter the number 2 the output should be 6 i suppose, although array count starts from 0 but the good old human counting starts from 1 (unless its the requirement of your code)... just saying

and for the code

your line 16 defines a const max=0; you can't change the value of const, so you linearSearch() function never runs

Hope it helps
Cruicial,

If what you want to do is enter 2 into getSearchNumber and have it print the value of 8. Then line 22 would be cout<<"The number "<<a[getSearchNumber]<<"was found"<<endl;. And the if else would not work because result would have no value or garbage.

If you want to search the array for a possible number then your program works fine as is.

Hope that helps,

Andy
Topic archived. No new replies allowed.