homework help of recursion

Write a recursive Boolean function isMember. The function should accept two arguments: an array and a value. The function should return true if the value is found in the array, false if the value is not found in the array.
Complete the following program by adding isMember function definition and testing it.


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
55
56
57
58
59
60
  #include <iostream>
using namespace std;


// Function prototype
bool isMember(int [], int, int, int);

const int ARRAY_SIZE = 10;

int main()
{
  // Create an array with some values in it.
  int numbers[ARRAY_SIZE] = {2, 4, 6, 8, 10, 12, 14, 16 ,18, 20};

  int x; //store the number into x
  int result; //hold the search

  //Get a number from user!
  cout << "Enter a value to search ";
  cin >> x;

  // Search for the values 0 through 20 in the array.
  //result = isMember(numbers, 0, ARRAY_SIZE - 1, x);

  //display the searach
  for (int x = 0; x <= 10; x++)
    {
      if (isMember(numbers, x, ARRAY_SIZE - 1, x))
        cout << x << " is found in the array.\n";
      else
        cout << x << " is not found in the array.\n";
    }


  return 0;
}
// write isMember function definition here
bool isMember(int arr[], int first, int last, int value)
{
  int middle;
  if (first > last)
    return -1;
  middle = (first + last)/2;

  if (arr[middle] == value)
    return middle;

  if (arr[middle] < value)
        return isMember(arr, middle + 1, last, value);

  else
        return isMember(arr, first, middle - 1, value);


}

the output doesnot come out the way i wanted. please help me =) thanks


Last edited on
The function should accept two arguments: an array and a value.

not sure how the function can be recursive if it accepts only 2 arguments – assuming the array argument is actually two – the name and size of the array and the value argument is the key to search by:
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
#include <iostream>
#include <iomanip>

bool isMember(const int numbers[], const int numbersSize, const int key)
{
    if (numbers[numbersSize] == key)
    {
        return true;
    }
    else if (numbersSize == -1)
    {
        return false;
    }
    else
    {
        return isMember(numbers, numbersSize - 1, key);
    }
}
int main()
{
  int numbers[] = {2, 4, 6, 8, 10, 12, 14, 16 ,18, 20};

  std::cout << std::boolalpha << isMember(numbers, sizeof(numbers)/sizeof(numbers[0]), 10) << " "
                        << isMember(numbers, sizeof(numbers)/sizeof(numbers[0]), 22) << "\n";
}
Topic archived. No new replies allowed.