-3

Wanted to know whether a for-loop is better or if I should stick with a while loop. And if so why or why not.

srand((unsigned) time(NULL));
bool result;
bool end = false;
int win, lose;
char answer;

win = lose = 0;
while (!end) {
    result = play_game();

    if (result) {
        printf("You win!\n\n");
        ++win;
    } else {
        printf("You Lose!\n\n");
        ++lose;
    }

    printf("Do you want to play again (y/n) ");
    if ((toupper(answer = getchar())) == 'Y') {
        end = false;
    } else if ((toupper(answer = getchar())) == 'N'){
        end = true;
    }
}
kron maz
  • 131
  • 1
  • 6

1 Answers1

0

I'd use a do-while as long as you're not limited to a certain amount of plays.

char answer;
do
{
    answer = toupper(getchar());
    // ...
} while (answer == 'Y');

The difference here is that the do-block will be ran at least one time. If the condition is met again (answer == 'Y'), then the do-block will be ran again, otherwise it'll break out.

Treyten Carey
  • 641
  • 7
  • 17