-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
80 lines (73 loc) · 1.96 KB
/
main.c
File metadata and controls
80 lines (73 loc) · 1.96 KB
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
// A number guessing game...
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
// Function Prototypes
int replay();
void clearBuffer();
int main()
{
srand(time(0)); // Seed RNG
int guess, attempt = 0; // stores user input & tracks attempts
int randNo = rand() % 100 + 1; // generate a random no. at range [1, 100]
// Replay on yes
do
{
// Validate User I/p
puts("\nGuess the number between 1 to 100");
while (scanf("%d", &guess) != 1 || guess > 100 || guess < 1)
{
clearBuffer();
puts("\nInvalid Entry! Please enter a number between 1 to 100!");
}
clearBuffer();
attempt++; // Update attempts
if (randNo < guess)
{
puts("Lower number please!");
}
else if (randNo > guess)
{
puts("Higher number please!");
}
else
{
(attempt > 1) ? printf("\nGreat job! You cracked it after %d attempts!\n", attempt) : puts("\nLegendary! First try success! (^0^)");
if (replay()) // replay call
{
// Reset random no., user attempts and winning guess
attempt = guess = 0;
randNo = rand() % 100 + 1;
}
}
} while (guess != randNo);
puts("\nThanks for playing! See you next time...(>w<)");
return 0;
}
// Function Definitions
// Clear input buffer
void clearBuffer()
{
int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
}
// Replay? Strict (Y/N) prompt
int replay()
{
printf("\nDo you want to play again? (y/n): ");
while (1)
{
char opt = tolower(getchar());
if (getchar() == '\n')
{
if (opt == 'y')
return 1;
else if (opt == 'n')
return 0;
}
else
clearBuffer();
puts("\nEnter y to play again and n to quit (@^-^@)");
}
}