Help with arrays in functions

Hey all, so for my CS class we were given the following code, i can read ans understand what part is doing what in it, but we are supposed to "add code to implement function search, which accepts an integer array of numbers, the array size, and an integer value" and i have no idea where to start. Any help would be greatly appreciated
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;
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;
}
OK so you have your function prototype their bool search(int arr[], int size, int val); I would add const before your array so it looks like bool search(const int arr[], int size, int val); Because your only searching the array you don't want to be able to change it. Another change is to not have size in your prototype. It will work but you are declaring another variable you don't need to have because Size is already a global varaible. so your prototype will look like bool search(const int arr[], int val); and your call to it will look like found = search(nums, n);

So after your main function you need to declare the function so it will look like

1
2
3
4
5
6
7
8
bool search(const int arr[], int val);
{
bool found;

//put code here to find if val is within array arr

return found;
}


After you add the code in their you should be pretty good to go. One side note, currently you don't seed your random number generator so you should be getting the same values every time. If you do want to seed it, where you declare your variables in the top main add srand(time(0));
Last edited on
Topic archived. No new replies allowed.