Select random letters in C++
This post will discuss how to select random letters in C++.
A common solution to generate a random number between 0 and RAND_MAX is using the rand() function, defined in the <cstdlib> header. We can use it to generate a random letter between some specific range, as shown below for ASCII lowercase alphabet range a-z:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> #include <ctime> int main() { srand(time(NULL)); char ch = 'a' + rand() % 26; std::cout << ch << std::endl; return 0; } |
Don’t forget to pass a seed to the function srand(), preferably the current time. To generate a random uppercase letter, do like:
|
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> int main() { char ch = 'A' + rand() % 26; std::cout << ch << std::endl; return 0; } |
We can easily extend the above solution to generate values in ranges a-z and A-Z:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <ctime> char randomLetter() { int r = rand() % 52; char base = (r < 26) ? 'A' : 'a'; return (char) (base + r % 26); } int main() { srand(time(NULL)); char ch = randomLetter(); std::cout << ch << std::endl; return 0; } |
Finally, you can generate a random letter from ASCII alphanumeric range or any other specific character range as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <ctime> int main() { srand(time(NULL)); std::string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; char ch = alphabet[rand() % alphabet.size()]; std::cout << ch << std::endl; return 0; } |
That’s all about selecting random letters in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)