After sticking with the same handful of languages for years, I decided to learn C.
I've written a guess the number game, where it generates a random number based on the difficulty level, and then you have 5 attempts of guessing the number.
If you guess incorrect, it will give you a clue by telling you if the answer is higher or lower than your last guess. I find the game to be pretty interactive, and wanted to get a code review to see how I could improve on it.
This is my first ever C program and I'm just looking to improve.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generate_random_number(int min, int max) {
srand ( time(NULL) );
return min + (rand() % (max - min));
}
void play() {
int difficulty = 1; // 1 = easy, 2 = medium, 3 = hard, 4 = insane
printf("1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\n");
printf("What level would you like to play: ");
scanf("%i", &difficulty);
int min = 0;
int max = 0;
int random = 0;
if (difficulty == 1) {
min = 0;
max = 25;
printf("You have selected to play easy\n\n");
}
else if (difficulty == 2) {
min = 0;
max = 50;
printf("You have selected to play medium\n\n");
}
else if (difficulty == 3) {
min = 0;
max = 75;
printf("You have selected to play hard\n\n");
}
else if (difficulty == 4) {
min = 0;
max = 100;
printf("You have selected to play insane\n\n");
}
random = generate_random_number(min, max);
int tries = 5;
int won = 0;
while (tries > 0)
{
int guess = 1000000; // just so it doesn't accidentally equal to random
printf("Guess a number %i to %i: ", min, max);
scanf("%i", &guess);
if (guess == random) {
won = 1;
break;
}
else {
if (guess > random) {
printf("Incorrect guess, the answer is lower than your guess!\n\n");
}
else {
printf("Incorrect guess, the answer is higher than your guess!\n\n");
}
}
tries -= 1;
}
if (won) {
printf("Congratulations, you have won the game!");
}
else {
printf("Sorry, you are out of tries.\n\n");
}
}
int main() {
while (1) {
play();
}
return 0;
}