-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.c
90 lines (81 loc) · 1.6 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <time.h>
#include <ctype.h>
// Function prototypes
void playGame();
int getRandomNumber(int min, int max);
int getUserGuess();
void checkGuess(int guess, int num);
bool playAgain();
int main()
{
// Seed the random number generator
srand(time(NULL));
do
{
playGame();
} while (playAgain());
printf("Thanks for playing!\n");
return 0;
}
void playGame()
{
int num = getRandomNumber(1, 100);
int guess;
do
{
guess = getUserGuess();
checkGuess(guess, num);
} while (guess != num);
}
int getRandomNumber(int min, int max)
{
return rand() % (max - min + 1) + min;
}
int getUserGuess()
{
int guess;
do
{
guess = get_int("Enter your guess (1-100): ");
if (guess < 1 || guess > 100)
{
printf("Invalid guess. Enter a number between 1 and 100\n");
}
} while (guess < 1 || guess > 100);
return guess;
}
void checkGuess(int guess, int num)
{
if (guess == num)
{
printf("Congratulations! You guessed the number\n");
}
else if (guess > num)
{
printf("Too high\n");
}
else
{
printf("Too low\n");
}
}
bool playAgain()
{
char response;
do
{
response = tolower(get_char("Do you want to play again? (y/n): "));
if (response == 'y')
{
return true;
}
else if (response == 'n')
{
return false;
}
printf("Invalid response. Enter 'y' to play again or 'n' to quit\n");
} while (true);
}