Sean.D Sean.D - 15 days ago 4
C Question

Programming in C, ending a while loop

I am new to C and I found 1 forum in C for ending a while loop and that one did not really help as with the break it still does not work. It gives me a "expected ; before break" or "int keep_playing=4" to end the loop. This is a simple rock paper scissors game and I am just working on the loop and going to soon worry about the logic portion. Here is my code.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
printf("Welcome to rock paper scissors!\n");
int keep_playing=5;
while (keep_playing==5)
printf("Press 'y' to play or 'n' to quit: ");
char playornot;
scanf("%c\n",&playornot);
if (playornot=='y')
printf("Ok.\n");
else (playornot=='y')
int keep_playing=4;

return 0;
}

Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    printf("Welcome to rock paper scissors!\n");
    int keep_playing=5;
    while (keep_playing==5) {
        printf("Press 'y' to play or 'n' to quit: ");
        char playornot;
        scanf("%c",&playornot);
        if (playornot=='y') {
            printf("Ok.\n");
        } else if (playornot=='n') {
            keep_playing=4;
        }
    }
    return 0;
}

Is how your code should look like. In your case, there was an infinite loop because the only line which was repeated was printf("Press 'y' to play or 'n' to quit: ");. This was caused by the luck of curly braces.

Then, you had a typo I would say - redundant int in int keep_playing=4. This declared another variable, visible only in this scope. Actually it should have caused the error when there were no curly braces, as it was the same scope at that moment.

And there was a third bug which noone mentioned before. If the entered character wasn't y it should have been n. Otherwise you should ask for another input or somehow decide how to deal with it.

And the fourth one was that yoou tried to scan two characters to char playornot. Removed \n from scanf.