Click here to Skip to main content
14,453,136 members
Rate this:
Please Sign up or sign in to vote.
See more:
I was given this code to start:
char s[21];

    for ( k = 0; k < 20; k++ )
        s[k] = ' ';
    s[20] = '\0';

    printf("|%s|\n", s);

I have to include the following into the code i have:
- place 5 random characters within string s
- symbol should be a lowercase character
- location/position must be within valid string

The final code should generate (without the periods, just spaces):
|...................|
|..l..gy..x...c|

the letters and spacing can be random, but must stay within the string

What I have tried:

I haven't been able to get past this:
char s[21];

    for ( k = 0; k < 20; k++ )
        s[k] = ' ';
    s[20] = '\0';

    printf("|%s|\n", s);
    printf("\n");

    return 0;
}

Any help would be appreciated as I really struggle with coding. Thanks!
Posted
Updated 2-Nov-19 0:55am
v2
Comments
Peter_in_2780 2-Nov-19 0:09am
   
Think about how you would do it with pencil and paper.
Note down those steps.
Translate them into code.
Compile and test.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Start by setting up a char array, which contains the characters you want to choose from. For "all lowercase characters" that would be:
char pickFrom[] = "abcdefghijklmnopqrstuvwxyz";
Then create a random number generator using srand: C library function - rand() - Tutorialspoint[^]
You can now use rand inside a loop to "pick" random characters from the array (using the modulus operator) and set them into your output string.

Give it a try: it's isn't hard to do if you think about it!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100