Answer:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int* createArray(int size) {
int* array = new int[size];
srand(time(0)); // seed random number generator
for (int i = 0; i < size; i++) {
array[i] = rand() % 100; // fill array with random numbers between 0 and 99
}
return array;
}
static int searchFunctionCalls = 0;
bool search(int* array, int size, int value, bool reverse) {
searchFunctionCalls = 0; // reset search function calls
if (reverse) {
for (int i = size - 1; i >= 0; i--) {
searchFunctionCalls++;
if (array[i] == value) {
return true;
}
}
} else {
for (int i = 0; i < size; i++) {
searchFunctionCalls++;
if (array[i] == value) {
return true;
}
}
}
return false;
}
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int* array = createArray(size);
int value;
cout << "Enter the value to search for: ";
cin >> value;
bool reverse;
cout << "Search left to right? (0/1): ";
cin >> reverse;
reverse = !reverse;
if (search(array, size, value, reverse)) {
cout << "Value found in array, number of search function calls: " << searchFunctionCalls << endl;
} else {
cout << "Value not found in array, number of search function calls: " << searchFunctionCalls << endl;
}
delete[] array;
return 0;
}
Step-by-step explanation:
In the above program, the createArray function creates a one-dimensional array of the size provided by the user and fills it with random integers between 0 and 99. The search function takes in the array, its size, the value to search for, and a boolean indicating whether the search should be done left to right or right to left. It uses a for loop to iterate through the array and check each element. A static variable searchFunctionCalls is used to keep track of the number of times the search function is called. The main function takes user input for the size of the array, the value to search for, and the direction of the search, and calls the createArray and search functions to perform the search. If the value is found, the program outputs the index of the element and number of calls to the search function. If the value is not found, it outputs the number of calls to the search function.