C++ Random

Introduction

Random number is generated using the rand() function. The rand() function generates a random number between 0 and RAND_MAX. To generate a random number between 1 and 100, use the formula rand() % 100 + 1.

Example:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
	int num;
	num = rand() % 100 + 1;
	cout << num;
}

When you run the above code, you'll find that the output is the same each time you run the program. This is because the random number generated is based on the seed value. To generate different random numbers each time you run the program, use the srand() function to set the

seed value
. The seed value is usually set to the current time.

A new seed value is set using the time() function from the ctime library.

Example:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
	
int main() {
	int num;
	srand(time(0));		// set seed value to current time
	num = rand() % 100 + 1;
	cout << num;
}

Task

Generate 6 random numbers between 1 and 49 to simulate mark six. The numbers should be unique.

Hints: After generating a random number, check if the number is already in the array. If it is, generate again.

Reference

C++ Random Number