generate random numbers and letters c++ code example

Example 1: getting a random letter in c++

char c;
    int r;

    srand (time(NULL));    // initialize the random number generator
    for (i=0; i<num; i++)
    {    r = rand() % 26;   // generate a random number
          c = 'a' + r;            // Convert to a character from a-z
          cout << c;
    }

Example 2: C++ generate a random letter

#include <iostream>

int main() {
    srand(time(0));
    std::cout <<"random uppercase = " << char('A' + rand() % 26) << std::endl;
    // or
    std::cout <<"random uppercase = " << char('a' + rand() % 26) << std::endl;
}

Tags:

Cpp Example