Random Letter help

I found this code in a different topic and i was a little confused on how it works. How does it create random letters when the only letter involved is 'a'. I thought you would need to have the whole alphabet in a string or something.

1
2
3
4
5
6
7
8
9
  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;
    }
Hi,

the thing about coding is that you have to be as lazy as possible

r = rand() % 26;
this will set the r value assigned randomly from 0-25

c = 'a' + r;
This will set the value of char c from a + (0 to 25)... the integer value of a is 97 (it actually doesn't matter here)... the add 25 (upper limit) to it you'll get z (ascii value 122).... in between you'll get the other characters randomly.....

HOPE IT HELPS


Thanks, That makes sense. But when i try to make it into a function i keep getting the same letter repeating.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <cctype>
#include <ctime>

using namespace std;
void x(char s, int n, int e);




int main() {
	
	char c='\n';
	int num=7;
	int r=0;
	x(c, num, r);
	
	

	system("pause");
	return 0;
}

void x(char s, int n, int e) {
	srand((unsigned int)time(0));    // initialize the random number generator
	for (int i = 0; i < n; i++)
	{
		e = rand() % 26;   // generate a random number
		s = 'a' + n;            // Convert to a character from a-z
		cout << (s);
	}
}

You don't need that many variables, I'm certain. It can be solved like this :
1
2
3
4
for (i = 0; i < num; i++) 
{
    cout << (char)('a' + rand() % 26) << endl;
}


But I actually recommend not using magic values. So 26 can be written as ('z' - 'a').

1
2
3
4
for (i = 0; i < num; i++) 
{
    cout << (char)('a' + rand() % ('z' - 'a')) << endl;
}


Or better yet :
1
2
3
4
i = -1; while (++i < num) 
{
    cout << 'a' + (char)(rand() % ('z' - 'a')) << endl;
}

Last edited on
Thanks, That makes sense. But when i try to make it into a function i keep getting the same letter repeating.

The problem is this one :
s = 'a' + n;

Should be :
s = 'a' + e;
Last edited on
Thanks a lot that worked. For the second method, can you explain how and why you 'char' in the cout?
That is called type-cast. It casts a value from an (int) to a (char).
http://www.cprogramming.com/tutorial/lesson11.html

You can also try removing the (char) type cast all you want. If the output is the same, then good for you. But if the output is a set of only digits, you should keep the (char) part.
Last edited on
Topic archived. No new replies allowed.