Problems with array

I have created a program for 'search' in int array..but how do i search against the array such as read 5 student names into the array and display the location of the matched name. i tried and tried,but fail.


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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
#include<string>
using namespace std;


int search(int data[], int size, int value)
{

	
	int lower, middle, upper;
	lower = 0;
	upper = size-1;
	
	while(true)
	{
		middle = (lower + upper)/2;
		if (data[middle] == value)
			return middle;
		else if (lower >= upper)
			return -1;
		else if (data[middle] > value)
			upper = middle -1;
		else
			lower = middle +1;
	}
	return 0;
}

void main()
{
	int name[5];

	for (int i=0;i<5;i++)
	{
		cin >> name[i];
	}


	int index;
	int input;

	cout << "\n\nSearch = ";
	cin >> input;

	
	index = search(name,5,input);
	
	
	if (index == -1)
		cout << "Not Found "<<endl;
	else
		cout << "Found at Location = " << index <<endl;

}
You're overcomplicating it.

Just do a loop like this:

1
2
3
4
5
6
for(size_t i = 0; i < size; ++i)
{
	if(value == data[i]) return i;
}

return -1;

Your array doesn't hold student names, though. It holds integers. You could adapt this to use std::string instead.
Looks like he wants to do a binary search. In order to do that you must have the input array sorted. Otherwise you'll have to do a linear search as filipe did. You can actually do a binary search with the std algorithm but that just returns bool true if found and false otherwise. Alternatively try lower_bound which returns an iterator. Again to use those kinds of searches the array must first be sorted!
http://cplusplus.com/reference/algorithm/sort/
http://cplusplus.com/reference/algorithm/lower_bound/
Topic archived. No new replies allowed.