-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevel_1_Task 2_Number Guessing Game.cpp
More file actions
65 lines (46 loc) · 1.8 KB
/
Level_1_Task 2_Number Guessing Game.cpp
File metadata and controls
65 lines (46 loc) · 1.8 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
#include <iostream>
#include <random> // for rand() and srand()
#include <ctime>
using namespace std;
// Number Guessing Game
// Objectives: i), ii), and iii)
int generateRandomNumber () {
srand (time (0)); // Seed the random generator
// To get a number in a specific range, say 1 to 10:
int lower = 1;
int upper = 10;
int rand_num = lower + rand() % upper; // i) Use the rand() function to generate random numbers
return rand_num;
}
int main () {
cout << "--------------------------------------------------------\n";
cout << "\t\t Number Guessing Game\n";
cout << "--------------------------------------------------------\n";
cout << "A number is chosen between 1 and 10." << endl << endl;
cout << "You have 5 attempts to guess the correct number." << endl;
int rand_num = generateRandomNumber ();
int guess;
int curAttempts = 0, maxAttempts = 5;
// ii) Implemented do-while loop to allow multiple attempts.
do {
cout << "Enter your guess: ";
cin >> guess;
if (guess != rand_num) {
curAttempts++;
if (curAttempts == maxAttempts)
cout << "You've exhausted all attempts. The correct number was " << rand_num << endl << endl;
else
cout << "You have " << (maxAttempts - curAttempts) << " attempts left" << endl << endl;
// iii) Provide feedback on whether the guess was too high or too low
if (guess < rand_num)
cout << "Your guess, " << guess << ", is too low." << endl << endl;
else
cout << "Your guess, " << guess << ", is too high." << endl << endl;
} else {
cout << "It took you " << curAttempts + 1 << " attempts to guess my number, which was " << rand_num << endl << endl;
cout << "Thanks for playing game! Have a nice day!";
return 0;
}
} while (curAttempts != maxAttempts);
return 0;
}