Professional Documents
Culture Documents
Random Numbers
Random Numbers
Manila
CITE – 002 Computer Programming 1
Non-graded/Extra work for programming practice
Random numbers
There is already a built in function in C++ that can generate a random number. See the code
below.
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
srand((unsigned) time(0));
int randomNumber = rand()%35;
cout << randomNumber << endl;
}
Where:
#include <cstdlib>
We need to include the cstdlib when using the random number in C++.
srand((unsigned) time(0));
Simple game
The simple game is an application of random which lets y guest what is the random number
between 0 and 1.
#include <time.h>
#include <iostream>
int main() {
srand((unsigned) time(0));
int g, random, score;
cout<<"Enter 3 if you want to quit.\n";
do{
//generate random number
random=rand() % 2;
cout<<"Enter your guess (0 or 1): ";
cin>>g;
if(g==random){
cout<<"Correct!\n";
}else{
cout<<"Incorrect!\n";
}
}while(g!=3);
}
Sample output:
Challenge
Modify the program on guessing the number if it is 0 or 1 so that it counts the total correct and
incorrect guest. After pressing 3, the program displays the total correct and incorrect guess.
Source code: