I'm writing a small toy program that guesses the number chosen by the user, but when I run it, it gets stuck in:
Is your number higher or lower? (h/l):
This is the code that I have written so far:
#include <stdio.h>
#include <stdlib.h> // includes srand() and rand()
#include <time.h>
#define MAX 100
#define MIN 1
int main(void)
{
time_t t;
char response;
int lower = MIN, higher = MAX, guess;
srand(time(&t)); //Initializes random number generator
guess = (random() % 100) + 1; // Initial guess
printf("Pick a number from 1 to 100. I'll try to guess it.\n");
printf("Is your number %d? (y/n): ", guess);
while ((response = getchar()) != 'y')
{
printf("Is your number higher or lower? (h/l): ");
while ((response = getchar()) == 'h' || response == 'l')
{
if (response == 'h') {
lower = guess;
guess = (higher - guess) / 2;
printf("Is it %d?: ", guess);
} else if (response == 'l'){
higher = guess;
guess = (higher - guess) / 2;
printf("Is it %d?: ", guess);
}
}
}
printf("Great!!\n");
return 0;
}
For some reason it doesn't enter the second loop, where I check if response
equals h
or l
.