Random Numbers in a fixed set - C++ Data Type

C++ examples for Data Type:Random

Introduction

Write a single statement that prints a number at random from each of the following sets:

a)  2, 4, 6, 8, 10. 
b)  3, 5, 7, 9, 11. 
c)  6, 10, 14, 18, 22. 

Demo Code


#include <cstdlib>
#include <ctime>
#include <iostream>

int main(int argc, const char *argv[]) {
    srand(time(NULL));//from   ww w .jav  a2s  .c  om

    std::cout << "Random number from each of the following sets: " << std::endl;
    std::cout << "\n2 4 6 8 10: " << 2 * (rand() % 5 + 1)
              << "\n2 5 7 9 11: " << 1 + (rand() % 5 + 1)
              << "\n6 10 14 18 22: " << 2 * (1 + (rand() % 5 + 1)) << std::endl;

    return 0;
}

Result


Related Tutorials