0

I am very new to programming and am working my way through some C basics. I am trying to write a very simple little bit of code that uses conditional statements. This program is meant to take the highest possible number and lowest possible number defined earlier and divide it by two and ask the user if its the number they are thinking of. If its too High it alters it, too low alters it, and asks again. The last statement is there for if anything other than the three desired letters entered.

However when I initiate this section of the code. It says the first printf statement, the "that is not a valid answer" printf statement, then repeats the first printf statement before waiting for user input. This happens at each beginning loop. (see below for input).

Any formatting with my loops that need to be changed? Please keep in mind I have been coding for about 4 weeks. Thanks!

//initiate a loop until the program guesses the right thing

do{
    guess = (lowest_possible + highest_possible)/2;
    printf("my guess is %d,am I right (Y) too high (H) or too low(L)?: ", guess);
    char user_response = getchar();
    if (toupper(user_response) == 'Y') {
        guess_check = 1;
    }
    else if(toupper(user_response) == 'H'){
        highest_possible = guess - 1;
        printf("Hmmm too high? Let me guess again. \n");
    }
    else if(toupper(user_response) == 'L'){
        lowest_possible = guess +1;
        printf("Hmmm too low? Let me guess again. \n");
    }
    else {
        printf("That's not a valid answer, please try again. \n");
    }
 }while(guess_check == 0);

OUTPUT:

my guess is 50,am I right (Y) too high (H) or too low(L)?: That's not a valid answer, please try again. 

my guess is 50,am I right (Y) too high (H) or too low(L)?:  H
That's not a valid answer, please try again. 

my guess is 50,am I right (Y) too high (H) or too low(L)?: Hmmm too high? Let me guess again. 

my guess is 25,am I right (Y) too high (H) or too low(L)?: That's not a valid answer, please try again. 

my guess is 25,am I right (Y) too high (H) or too low(L)?: 
melpomene
  • 79,257
  • 6
  • 70
  • 127

0 Answers0