-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_guessing_game.c
81 lines (67 loc) · 2.19 KB
/
number_guessing_game.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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int MIN = 1; // The minimum value for the guessing range
const int MAX = 100; // The maximum value for the guessing range
int guess; // The user's current guess
int tries; // The number of attempts the user has made
int answer; // The randomly generated correct answer
int lastGuess; // The user's last guess
// Function to generate a random number within a specified range
int randomNumber(int lower, int upper)
{
srand(time(0)); // Seed the random number generator with the current time
return (rand() % (upper - lower + 1)) + lower;
}
// Function to check if a string input represents a valid integer
int isInteger(char input[])
{
for (int i = 0; input[i] != '\0'; i++)
{
if (input[i] < '0' || input[i] > '9')
{
return 0; // Not a valid integer
}
}
return 1; // Valid integer
}
int main()
{
// Generate a random number and initialize variables
answer = randomNumber(MIN, MAX);
printf("Welcome to the Number Guessing Game!\n");
do
{
char input[8]; // Buffer to store user input
printf("Enter your guess (%d-%d): ", MIN, MAX);
scanf("%s", input);
// Check if the input is a valid integer
if (!isInteger(input) || atoi(input) > MAX)
{
printf("Please enter a valid number between %d and %d.\n", MIN, MAX);
tries++;
continue;
}
guess = atoi(input); // Convert the valid input to an integer
if (guess < answer)
{
printf("Guess higher!\n");
tries++;
}
else if (guess > answer)
{
printf("Guess lower!\n");
tries++;
}
lastGuess = guess;
} while (guess != answer);
// Display a congratulatory message and the number of tries
printf("Congratulations! You guessed the correct number: %d\n", answer);
if (tries == 1) {
printf("You tried: %d time, and got it on the %d try\n", tries, tries + 1);
}
else {
printf("You tried: %d times, and got it on the %d try\n", tries, tries + 1);
}
return 0;
}