Overview: C++ functions and recursion.
As you write your program please remember to pay attention to issues of style, including:
Write a program that allows the user to search for a target value in an array using binary search. Your program should ask the user to enter a sorted array and a target value and then call a binary search function. Write your binary search function such that it is recursive.
//search for target in array a[] between positions start and //end. return the index where it is found, or -1 if not found int binarySearch(int a[], int start, int end, int target) { } void readArray(paramter-list) { } void provideFeedback(parameter-list) { } int main() { int a[100], n, target; //read the array from user and set n to its size readArray(a,n); cout << "Enter target: "; cint >> target; int index; index = binarySearch(a, 0, n-1, target); //let the user know whether the target has been found or not provideFeedback(index); }Remember how binary search works: you compare the target with a[middle], and depending on the result of the comparison you search for it left or right. How would you express this recursively? That is, can you express the problem of searching left (right) as another binary search problem?
Write a program that implements a binary-search-like guessing game: the program picks a random number and asks the user to guess it; the user is told, for each guess, whether it is too high or too low.
Your program should:
Design your program so that your main program looks exactly as below:
int main() { const int GUESS_LIMIT = 1024; const int NB_GUESSES = 10; //seed the random number generator with the current time so that you //get different numbers each time you run it (you don't need to do //anything further with this). srand(clock()); //explain the program to the user. you do not need to ask whether //they want to use it --- assume they do. explainProgram(); //generate a target from 1 to GUESS_LIMIT int target = generateTarget(GUESS_LIMIT); //allow the user to play the guessing game; if the user does not //guess te answer in GUESS_LIMIT guesses they lose int won = playGuessingGame(GUESS_LIMIT, target, NB_GUESSES); //let them know whether they won or not provideFeedback(won); }Note that the way the functions are used in main tells you exactly what the function header (the first line of a function that specifies the return type, function name and parameter list) should look like. For example, given this function:
int target = generateTarget(GUESS_LIMIT);you know that the function returns an integer value and has a single parameter which must be an integer. So the function will look like this:
int generateTarget(int upperLimit) { //generate a random number in the range 1..upperLimit and return this //value }