This question already has an answer here:
I'm new to programming in C and have been given the task of creating a 2D array that stores random letters from A-Z using the random () function. I know how to do random numbers.
nextvalue = random ( ) % 10001;
but am unsure on how exactly to create a random character. I know that you can use ASCII to create a random character using the range 65 - 90 in the ASCII table. Can anyone help me come up with a solution? I would greatly appreciate it.
You should assume something about the character encoding of your system. Let's suppose it is ASCII or UTF-8 and let us restrict ourselves to the 26 upper-case letters ABC...XYZ of the latin alphabet.
Then you could code:
This won't work on EBCDIC. You could also try
which would work with any encoding (including EBCDIC, ASCII, UTF-8, ISO-Latin-1) ....where each A...Z letter is encoded by a single
char
.But this is an interesting answer explaining why
random() % 26
is wrong. In my naive non-expert view, it is good enough.Replacing
random() % 26
bymyrandomlt26()
where we have definedshould be slightly better (Very often the
do
...while
loop above should run once).However, learn more e.g. about Unicode, you'll discover that there are some human languages where the very notion of letter (or upper-case) is not as trivial as you believe.
I'm not an expert on these matters, but urban legend says that strangely the French
œ
is not a letter (but just a ligature) because the French representative at some ISO meeting was sick when it was discussed. At French school, I recall having learned (probably in 1966-1972) that it is not a letter (but not hand-writing the ligature -which has a special name "E dans l'O" in French- was a spelling mistake), but some people believe the opposite. Usually accented letters likeé
orà
are considered letters in French (but their UTF-8 encoding takes several consecutivechar
....). Likewise I believe and have learned that the cyrillic soft-signь
is not a letter, even if it looks like one. Defining what is a letter in arabic, hebrew, korean, cherokee, thai ... should also be fun and matter of endless debates...I think you have already solved this problem. You just need to think harder and tinker more with it. In C you can easily display any ASCII character in Dec form. Here is the ASCII Table for reference. For example
So it is probably the same as generating a random number between 65 and 90. Hope this helps ;) Am also new to C with some background in C++.