Previous Lecture Outline
Ternary Operators
Switch in C++
Lecture Outline
Generating Random Numbers
Class Activities for Random numbers
Generating Random Numbers
• You can use the rand() function to obtain a random integer.
• This function returns a random integer between 0 and RAND_MAX.
RAND_MAX is platform-dependent constant.
• The rand() function’s algorithm uses a value called the seed to control
how to generate the numbers. By default, the seed value is 1.
• If you change the seed to a different value, the sequence of random
numbers will be different. To change the seed, use the srand(seed)
function in the cstdlib header file.
• srand(time(0)); produces a different output every time you run the
program.
Generating random numbers:
• To obtain a random integer between 0 and 9, use
rand() % 10
• To obtain a random integer between 0 and 99, use
rand() % 100
Activity: Generating Random Numbers
• The program may be set up to work as follows:
Step 1: Generate two single-digit integers into number1 and
number2.
Step 2: Ask user to enter y if he/she wants to play this game.
Step 3: if user enters yes Prompt the user to answer “What is
number1 + number2?”
Step 4: Check the student’s answer and display whether it is
correct. If user guess correct answer, display Congratulations
otherwise print sorry
Generating random number between lower and upper bound
Example:
Generating random numbers between 1 and 6 where 1 = minimum value and 6 =
maximum value
Formula = (rand()%(maximum value-minimum value+1))+minimum value
Tasks
• Which of the following is a possible output from invoking rand()?
323.4, 5, 34, 1, 0.5, 0.234
a. How do you generate a random integer i such that 0<=i < 20?
b. How do you generate a random integer i such that 10<=i<=20?
c. How do you generate a random integer i such that 10 <=i<=50?
Solution for c
low=10
high = 50
rand()%(high-low+1)+low
d. Find out what RAND_MAX is on your machine.
Task
Write a program which ask user to generate a random number
between 1 and 3 and print apple if random number is 1, prints,
grapes if random number is 2 and prints peach if number is 3 (note
use switch)
Next Lecture
For loop
While loop