[Solved] Print a character a random number of times in C [closed]


You can print that character a random number of times in the following way:

int rand = 1 + (rand() % maximum);

for (int i = 0; i < rand; ++i) {
    printf("%c", RANDLOWER);
}

printf("\n");

Replace maximum with the max number of characters you want to be printed.

The reason I add the 1 to the rand() % maximum is because that calculation can never result in the number you provided. It can also result in 0. By adding 1, I am assuring that a character is always printed, and any number of that character can be printed from 1 to the maximum.

I then use a for loop to repeat the printing process as many times as needed, and then once the iteration is done I print “\n”, which is the newline character. It is not necessary, but it assures that the next text to appear will be on a new line.

As a note to the code you posted, you’ll need to type the RANDLOWER variable.

solved Print a character a random number of times in C [closed]