Skip to content

Instantly share code, notes, and snippets.

@mr-fool
Last active August 29, 2015 14:03
Show Gist options
  • Save mr-fool/1e47960faefc4d0c742e to your computer and use it in GitHub Desktop.
Save mr-fool/1e47960faefc4d0c742e to your computer and use it in GitHub Desktop.
A guessing game: practicing generating random number and goto statement
/*Cleaner Version*/
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main (void) {
unsigned guess; //user guess
unsigned answer; //the computer random answer
Guess:
printf("Guess a number between 1-10\n");
scanf("%u", &guess);
printf("Your guess is %2u\n", guess);
srand(time(NULL)); //randomizing the number using seed
answer = 1 + (rand() % 10 );
printf("The answer is %2u\n", answer);
if (answer != guess) {
printf("Your guess is incorrect, please try again\n");
goto Guess;
}
else {
printf("Your guess is correct\n");
}
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main (void) {
unsigned guess; //user guess
unsigned answer; //the computer random answer
Guess:
printf("Guess a number between 1-10\n");
scanf("%u", &guess);
printf("Your guess is %2u\n", guess);
srand(time(NULL)); //randomizing the number using seed
answer = 1 + (rand() % 10 );
printf("The answer is %2u\n", answer);
if (answer == guess) {
printf("Your guess is correct");
exit(0);
}
else {
//printf("%u\n", answer); //testing purpose
printf("Your guess is incorrect, please try again\n");
goto Guess; //looping
}
return 0;
}
allFiles: guess.c
gcc -Wall guess.c -o guess.out -lm
clean:
rm *.o guess.out
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment