
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ Program to Use rand and srand Functions
Random numbers can be generated in C++ using the rand() function. The srand() function seeds the random number generator that is used by rand().
A program that uses rand() and srand() is given as follows −
Example
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(1); for(int i=0; i<5; i++) cout << rand() % 100 <<" "; return 0; }
Output
The output of the above program is as follows −
83 86 77 15 93
In the above program, the output will be same on every program run as srand(1) is used..
To change the sequence of random numbers at every program run, srand(time(NULL)) is used.A program to demonstrate this is given as follows −
Example
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main() { srand(time(NULL)); for(int i=0; i<5; i++) cout << rand() % 100 <<" "; return 0; }
Output
The output of the above program is as follows −
63 98 17 49 46
On another run of the same program, the output obtained is as follows −
44 21 19 2 83
- Related Articles
- rand() and srand() in C
- rand() and srand() in C/C++
- What is the use of randomize and srand functions in C language?
- Golang program to show use of rand package
- PHP srand() Function
- C program to find sum, max and min with Variadic functions
- srand() function in PHP
- PHP rand() Function
- How to pass objects to functions in C++ Program?
- Write a C program to work on statements using functions and loops
- When to use anonymous JavaScript functions?
- What is the use of sprintf() and sscanf() functions in C language?
- rand() function in PHP
- How to use DATETIME functions in Oracle?
- How can I use RAND() function in an ORDER BY clause to shuffle MySQL set of rows?

Advertisements