Program must be written in C++: Write a recursive Boolean function isMember. The
ID: 3840042 • Letter: P
Question
Program must be written in C++:
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.
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 10;
// Function prototype
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. ";
else cout << x << " is not found in the array. "; }
return 0;
}
Explanation / Answer
#include <iostream>
using namespace std;
const int ARRAY_SIZE = 10;
// Function prototype
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. ";
else cout << x << " is not found in the array. "; }
return 0;
}
bool isMember(int numbers[], int x, int size) {
if(size ==0){
return false;
}
else{
if(numbers[size-1] == x){
return true;
}
else{
return isMember(numbers,x, size-1);
}
}
}
Output:
0 is not found in the array.
1 is not found in the array.
2 is found in the array.
3 is not found in the array.
4 is found in the array.
5 is not found in the array.
6 is found in the array.
7 is not found in the array.
8 is found in the array.
9 is not found in the array.
10 is found in the array.
11 is not found in the array.
12 is found in the array.
13 is not found in the array.
14 is found in the array.
15 is not found in the array.
16 is found in the array.
17 is not found in the array.
18 is found in the array.
19 is not found in the array.
20 is found in the array.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.