Reputation: 21
So I´ve read multiple answers and learnt different ways of generating random characters. I've come to like this attempt:
rand()%('z'-'a'+1)+'a';
I have used this method for quite a while, but I´ve come to understand that I can write it like this as well:
rand()%(26)+'a';
Now my question is, why does this work? What does the 'z'-'a' mean, and likewise, what does 26 mean? I know the characters have a numerical value, but that´s all I have been able to scrape from my attempts of trying to understand this.
Upvotes: 0
Views: 62
Reputation: 144
That's because of the ASCII value for all of these characters. You just need to search for the ASCII Table and you'll find out that the ASCII value for 'a' is 97, and for 'z' is 122. Therefore (122-97+1) is equal to 26. When you store a char into a variabile, you are storing its ASCII value, thus operators such as +, -, ... Are done using the ASCII value of their addends.
Upvotes: 1
Reputation: 18493
In a computer, letters are stored as numbers.
The lower-case letter a
is stored as 97 and the lower-case letter z
is stored as 122.
So the C expression myVariable='a';
is the same as the C expression myVariable=97;
.
On the other hand, 'z'-'a'+1
is the same as 122-97+1
which is the same as 26
.
Using the expression rand()%26+'a'
you first generate a random number in the range 0...25 (using rand()%26
). Then you add the value 97
to the result (because xxx+'a'
is the same as xxx+97
).
Note that rand()%26+'a'
does not mean: rand()%(26+'a')
but: (rand()%26)+'a'
.
As a result, you have a random number in the range 97...122.
This is the range of numbers that represent the lower-case letters a
...z
.
Upvotes: 2