Coffee Mug
Coffee Mug

Reputation: 47

How to make code loop back around after a condition of if, C guessing game

I'm stuck on the problem of trying to make my code loop back around after a condition.

I'm asking player 1 to enter a number between 0 and 99, if they enter anything outside of that the code should ask them to retry this. The problem is I honestly have no idea how to enable that from my code. This is what I have so far, I don't understand how to throw a while loop in here to have it circle back:

  int secretnumber;
  int guesses;

  printf("Player 1: Type a number between 0 and 99 and press return:\n");
  scanf("%d",&secretnumber);

  if (secretnumber > 99 || secretnumber < 0)
    printf("Secret number cannot be greater than 99 or below 0.");

  else
      printf("Type the number of guesses that player 2 gets and press return: \n");
      scanf("%d",&guesses);

I'm new to this and fully aware of how incompetent I probably sound, so I apologize in advance for that.

Upvotes: 1

Views: 342

Answers (1)

wildplasser
wildplasser

Reputation: 44250

  • continue; will skip the rest of the loop body and reiterate the loop
  • break; will jump out of a loop and to just after the loop body.

 int secretnumber;
 int guesses;

while (1)  {
  printf("Player 1: Type a number between 0 and 99 and press return:\n");
  scanf(" %d",&secretnumber);

  if (secretnumber > 99 || secretnumber < 0) {
    printf("Secret number cannot be greater than 99 or below 0.\n");
    continue;
    }
 break;
 }

printf( "Type the number of guesses that player 2 gets and press return: \n");
scanf(" %d",&guesses);

BTW: you should also test the return value you get from scanf(), it is the number of successful assignments, or -1 for EOF.

And: you can simplify the above loop by inverting the condition.


Upvotes: 1

Related Questions