How do you generate a random number between 1 and 6 in C++?

 rand():

rand() function in C++ returns a positive number within the range of 0.0 to rand_max(). the disadvantage of using this function is that if you generate many random numbers employing a loop, this function generates an equivalent sequence of numbers whenever the program is executed. However, if you would like to use this function to get different numbers whenever the program runs, you want to use srand() function with the rand() function.

srand(): srand() function seeds a pseudo-random number generator that's

employed by the rand() function. The default seed value for rand() is 1. Following is that the syntax for using srand():

Note: Always define the time header file. if you do not define the time header file the compiler gives or throws an error

  1. #include <cstdlib> 
  2. #include <ctime> 
  3. #include <iostream> 
  4. using namespace std; 
  5. int main() 
  6. { 
  7. srand((unsigned) time(0));  
  8. int randomNum = (rand() % 6) + 1;  
  9. cout << "The random number generated is: "<<randomNum << endl;  
  10. } 


Comments

Popular posts from this blog

proassignment help backlink data index 41

Programming shark backlink data index 67

AHM Backlink Data Index 95