Teo Chuen Wei Bryan - 8 months ago 42

C++ Question

I'm trying to generate an array of both upper and lower case letters at the same time.

I do understand the logic behind generating two seperate cases of letters.

`rand() % 26 + 65 // generate all the uppercase letter`

while

`rand() % 26 + 97 // generate all the lowercase letter`

I tried googling how to generate both of them together and here is what i got.

`rand() % 26 + 65 + rand() % 2 * 32 // generate both upper and lowercase letter`

Unfortunately, they did not exactly explain the logic behind it and i do not wish to just blindly copy and paste it into my assignment. Been searching high and low for the logic behind the

`rand() % 2 * 32`

`rand()`

`rand()`

Any help will be appreciated.

Answer

Observe that the `32`

is the difference between `65`

and `97`

, i.e. the difference between ASCII codes of uppercase and lowercase letters.

Now let's take `rand() % 26 + 65 + rand() % 2 * 32`

apart:

`rand() % 26 + 65`

generates a random uppercase letter;`rand() % 2 * 32`

generates either`0`

or`32`

, thereby converting the uppercase letter into its lowercase counterpart half the time.

A different, more verbose way, to rewrite this expression would be:

```
letter = rand() % 26 + 65;
if (rand() % 2) {
letter += 32;
}
```