Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Technological Institute of the Philippines

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));

- call this only one time in your code


- this allows the program to generate a random number. Without this line, you will notice
that your output will be the same everytime you run it.
 int randomNumber = rand()%35;

- the rand() is the function generating the number


- rand() % 35 asures that the generated random number is between 0 to 34.
- You can change the 35 based on your limit dispay of random number.
- rand() % 100 + 1 means range is 1 to 100
- rand() % 30 + 1985 means range is 1985 – 2014

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>

using namespace std;

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:

You might also like