How can I generate random uppercase letters in C?

Hello,

Below is what I tried. I can only use getchar/putchar for IO. How would I go about randomly generating 40 uppercase letters? I know that uppercase letters are 65 - 90 on the ASCII table, just not sure how to execute this properly.

Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void getRandomStr(){

    char str[40];
    int i;

    for (i = 0; i < 40; i++){

    char c = rand() % 26;

    str[i] = c;

 }

}
Try char c = 'A' + rand() % 26; or str[i] = 'A' + c; or if you really want you can simply add 65 which would be the same as adding 'A'[/code]
^^Thanks! I actually figured it out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void getRandomStr(){


    char str[40];
    int i;

    for (i = 0; i < 40; i++){

        char c = (90 - (rand() % 26));

        str[i] = c;

    }

    for (i = 0; i < 40; i++){

putchar(str[i]);

    }

}


Just need to see how I can replace the printf() with putchar(). Working on it now.

Edit: guess you just replace the printf() with putchar(str[i]); Seemed easy enough.
Last edited on
Seems a bit obfuscated doing it that way or even char c = 'Z' - rand() % 26; which is equivalent to what you are doing. Most people would start from the first letter and add on to it instead of starting from the back and counting down.
I'm wondering why it's generating the same letters every time. The letters below are generated via online compilers, as well.

MDOIYYNJYSXWZIALDPPBSRWWJHXWCIQNLDUICHQB
How are you seeding it? I would suggest: srand(time(NULL));
Topic archived. No new replies allowed.