Search function in array?

I have been trying to figure this out for 2 days and I keep getting errors, and I am just about to lose it haha.

My teacher says to "Add code to implement function search, which accepts an integer array of numbers, the array size and an integer value . The function returns true if the passed integer value is in the array and false, otherwise"

I understand I need a for loop to do this, but I am not sure where it is supposed to go or really
how to set up the function.

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
#include <iostream>
using namespace std;
bool search(int arr[], int size, int val);
const int SIZE = 25;
int main()
{
	int nums[SIZE]; //array declaration
	bool found;
	int n;

	//initialize array nums
	for (int i = 0; i < SIZE; i++)
	{
		nums[i] = rand() % 251;
	}
	//display the content of array nums
	cout << "\n***********************\n";
	for (int i = 0; i < SIZE; i++)
	{
		cout << nums[i] << "\t";
	}
	cout << "\n***********************\n";
	cout << "please enter a number between 0 to 250" << endl;
	cin >> n;
	found = search(nums, SIZE, n);
	if (found)
		cout << n << " was found in our data set!\n";
	else
		cout << n << " was NOT found in our data set!\n";
	return 0;

}
well you need to write the function bool search(int arr[], int size, int val)

you will need the for loop that goes through the array store the value of each element into a temp int variable and use an if else if statement to check whether the numbers match or not continue to the end and return true or false and in the If statement you have put

if (found == true)
data was found

else if
data was not found
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool search(int ary[], int size/*of array*/, int num/*to search for*/){
	
	bool flag = false;
	int i = 0;

	while (i < size && !flag){

		if (ary[i] == num)
			flag = true;

		i++;

	}

	return flag;
}
Thanks so much for the help guys, I keep getting an error on the bracket right after the function saying it is expecting a ;. Any suggestions?
Topic archived. No new replies allowed.