Guess the number

Write a program that asks the user to pick a number between 1 and 100. The program should then guess what the number is, asking the user at each guess if the correct number has been found. If the guess is incorrect, the user should state wether the guess was too low or too high. The program should do this in as few tries as possible (i.e. a simple loop that goes from 1 to 100 is not sufficient!).

I'm a beginner and have been trying with this for some time now but not able to do it, any help would be well appreciated :)
Well, you need to post your code and explain which parts you're having trouble with.
How do i make the program guess a random number? Do i let it guess if the number is 50 to begin with and if it's over 50 i work my way up and same goes for it's below 50?
Just use the information the user passes to improve the probability of getting it right until it's 100%. Define a lower and an upper bound and reset them accordingly when the user informs whether it's too low or too high.
well you would start off with it guessing a random number between 1 and 100 rand()%100, and then as the cpu is told whether the number is lower or higher than its last guess constrict the range within which the random number is chosen.

Post some code, everybody is wary of helping people who don't post any code as nobody wants to do someones homework for them without them even making an effort first.
shouldn't it be rand()%100+1?
Not sure, but i think otherwise 0 is also possible
yeah my bad
Just do it like you would: keep taking the middle of the remaining possible range - it will take at most ceil(log2(n+1)) tries when 1 is the lower limit and n is the upper number limit.
this should help:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <cstdlib>

int main()
{
	int p = 0;
	do {
		int i = rand()%100+1, v;
		printf("Enter the number: ");
		scanf("%d", &v);
		if(v==i)
			printf("Correct\n");
		else
			printf("Wrong the number was: %i\n", i);
	} 
	while(++p < 5);
	return 0;
}

not tested.
Last edited on
Write a program that asks the user to pick a number between 1 and 100.
The program should then guess what the number is, asking the user at each guess if the correct number has been found.
my bad
Topic archived. No new replies allowed.