C Program to write a number guessing game
Write a program that asks the user to think of a number between 1 and 10[but the solution I give below is a general solution]. The program has to guess the number in the mind of the user. Implement this algorithm.
- Divide the range 1 - 10 into two halves. Ask the user whether his number is in the lower half, i.e., from 1 to 5. Note that 5 is the midpoint of 1 and 10.
- If the user says yes, then you can assume that the number is between 1 and 5. Now divide the range 1-5 into two halves, and ask him whether the number is in the lower half, i.e., between 1 and 3. Note that 3 is the midpoint of 1 and 5.
- If the user says no, then you can assume that the number is between 3 and 5. Then divide this range into two halves, and repeat the algorithm.
- The search will stop when the midpoint becomes equal to either the lower boundary or the upper boundary of the range.
int main() { int numberFrom = 0, numberTo = 10; int midPoint = (numberFrom + numberTo)/2; printf("Think between %d and %d.", numberFrom, numberTo); cout << endl; while(true) { printf("Is it less than %d ?", midPoint); char yesno; cin >> yesno; if(('y' == yesno) || ('Y' == yesno)) { numberTo = midPoint; } else { numberFrom = midPoint; } // calculate new midpoint midPoint = (numberFrom + numberTo)/2; // if midpoint is at either border // we have found it if( (numberFrom == midPoint) || (numberTo == midPoint)) { printf("Is it more than %d ?", numberFrom); cin >> yesno; if(('y' == yesno) || ('Y' == yesno)) { cout << "It is: " << numberTo << endl; } else { cout << "It is: " << numberFrom << endl; } break; } } return 0; }
My C/C++ Videos on Youtube
Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.
This Blog Post/Article "C Program to write a number guessing game" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2020-02-07. Published on: 2016-03-18