Please help

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.

my output is just "not found" for the numbers in my array

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

const int ARRAY_SIZE = 10;

bool isMember(int [], int, int);

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

  // Search for the values 0 through 20 in the array.                                                                                                                                
  for (int x = 0; x <= 20; x++)
    {
      if (isMember(numbers, x, ARRAY_SIZE))
        cout << x << " is found in the array.\n";
      else
        cout << x << " is not found in the array.\n";
    }

  return 0;
}


bool isMember(int numbers[], int x, int ARRAY_SIZE)
{

  if (numbers[ARRAY_SIZE] == numbers[ARRAY_SIZE])
    return false;
  if (numbers[ARRAY_SIZE]== x)
    {
      return true;
    }
    else
    {
      return isMember(numbers + 1,x, ARRAY_SIZE);
    }
}
1. No need to pass ARRAY_SIZE to isMember: it's a global constant.

 
  if (numbers[ARRAY_SIZE] == numbers[ARRAY_SIZE])


2. This will always be true, since its logical equivalent would be "if A is equal to A". Also, it serves no purpose here.

3. In this code, "numbers[ARRAY_SIZE] == x" means "The value held at number[10] is equal to x"; it wouldn't be useful to search through the array in the first place, and in this case number[10] doesn't even exist since numbers has a size of 10 - ie. goes from numbers[0] to numbers[9].

4. A way to make your function recursive would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  bool isMember(int numbers[ARRAY_SIZE], int x, int i)
  {
    if (i < ARRAY_SIZE)
    {
      if (numbers[i] == x)
      {
        return true;
      }
      else
      {
        isMember(numbers, x, i+1)
      }
    }
    else
    {
      return false;
    }
  }
This appears to be a popular question lately: http://www.cplusplus.com/forum/beginner/212751/#msg994013
Topic archived. No new replies allowed.