### number guessing game binary search

so i am still relatively new to c++ and trying to follow the book, i get the concept of binary search but i can't seem to put it in affect. can anybody help me try solve this. Any help and all help greatly appreciated.

Basically i need to make a number guessing game where user thinks of a numbver from 1 - 100 and the machine will try to guess it in the least number of times. Once it guesses the number it will also say how many tries it took to guess.

my code so far is

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758`` ``````#include using namespace std; const int MAX = 100; int main() { char ch; cout << "Think of an integer number between 0 and " << MAX<> choice; if ('y' == choice) { return middle; } else if ('n' == choice) { cout << "Is it higher or lower? " << endl; cout << "Press h for higher and l for lower " << endl; cin >> choice; if ('h' == choice) { first = middle + 1; } else if ('l' == choice) { last = middle - 1; } } } cin.get(); cin.get(); return 0; }``````
Separate/Abstract your number from your search. Binary search only works on a sorted list. It assumes depending on the algorithm that data is sorted from least to greatest from left to right.

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758`` ``````#include using namespace std; #ifndef MAX #define MAX 10 #endif int main(int argc, char** argv[]) { char ch; cout << "Think of an integer number between 0 and " << MAX<> choice; //search until found or the entire x*log2(N) occurrences are iterated through while (first <= last && choice == 'n') { middle = (first + last) / 2; if (set[middle] < search) { first = middle + 1; } else if (set[middle] > search ) { last = middle - 1; } else { ` break; //found } } search = set[middle]; }//if done cin.get(); cin.get(); return search; }``````

You shouldnt have to query the user if the number is higher or lower because binary search already assumes the set is in ORDER. If your set is not ordered then you must order it.

EDIT:
for a number guessing game you don't need any search algorithm. All you need to do is generate or store a random number and give the user a certain number of attempts to guess it right before they lose. All you need is an infinite loop and if statements and bool checking. No need for binary or linear search here.
Last edited on
ah how do you generate a random number? and for the infinite loop we use while loop right? and whats bool check
Topic archived. No new replies allowed.