The lottery program involves generating random numbers, comparing digits, and using Boolean operators.
Suppose you are to develop a program to play the lottery. The program randomly generates a lottery of a two-digit number, prompts the user to enter a two-digit number, and determines whether the user wins according to the following rule:
- If the user input matches the lottery number in the exact order, the award is $10,000.
- If all the digits in the user input match all the digits in the lottery number, the award is $3,000.
- If one digit in the user input matches a digit in the lottery number, the award is $1,000.
Note that the digits of a two-digit number may be 0. If a number is less than 10, we assume the number is preceded by a 0 to form a two-digit number. For example, number 8 is treated as 08 and number 0 is treated as 00 in the program. Listing 3.7 gives the complete program.
LisTing 3.7 Lottery.cpp
1 #include <iostream>
2 #include <ctime> // for time function
3 #include <cstdlib> // for rand and srand functions
4 using namespace std;
5
6 int main()
7 {
8 // Generate a lottery
9 srand(time(0));
10 int lottery = rand() % 100;
11
12 // Prompt the user to enter a guess
13 cout << “Enter your lottery pick (two digits): “;
14 int guess;
15 cin >> guess;
16
17 // Get digits from lottery
18 int lotteryDigit1 = lottery / 10;
19 int lotteryDigit2 = lottery % 10;
20
21 // Get digits from guess
22 int guessDigit1 = guess / 10;
23 int guessDigit2 = guess % 10;
24
25 cout << “The lottery number is ” << lottery << endl;
26
27 // Check the guess
28 if (guess == lottery)
29 cout << “Exact match: you win $10,000” << endl;
30 else if (guessDigit2 == lotteryDigit1
31 && guessDigit1 == lotteryDigit2)
32 cout << “Match all digits: you win $3,000” << endl;
33 else if (guessDigit1 == lotteryDigit1
34 || guessDigit1 == lotteryDigit2
35 || guessDigit2 == lotteryDigit1
36 || guessDigit2 == lotteryDigit2)
37 cout << “Match one digit: you win $1,000” << endl;
38 else
39 cout << “Sorry, no match” << endl;
40
41 return 0;
42 }
The program generates a lottery using the rand() function (line 10) and prompts the user to enter a guess (line 15). Note that guess % 10 obtains the last digit from guess, and guess / 10 obtains the first digit from guess, since guess is a two-digit number (lines 22-23).
The program checks the guess against the lottery number in this order:
- First, check whether the guess matches the lottery exactly (line 28).
- If not, check whether the reversal of the guess matches the lottery (lines 30-31).
- If not, check whether one digit is in the lottery (lines 33-36).
- If not, nothing matches and display “Sorry, no match” (lines 38-39).
Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.