Score:-1

how to generate random number

us flag

I want to generate a few random numbers in the range 0-999 and store them in an array. This is my code:

void randnum(int number)
{
    int i;
    int num;
    int arr[11];
    printf("%d", number);
    for (i = 0; i < number; i++) 
    {
        num = rand() % 999;
        arr[i]=num;
    }       
    for(i=0;i<number;i++)
        printf("%d \n", arr[i]);
    
}

The output is:

6478 664 153 268 500 997

Am I doing it right? Why does my output have number 6478 which is not in the 0-999 range?

user10489 avatar
in flag
Note that using rand()% will produce an uneven distribution. Sometimes this matters.
Score:2
ru flag
printf("%d", number);

This will output number('6') but there is no newline after it. Try removing this line or change it to

printf("%d\n", number);
user15907922 avatar
us flag
ahh yes. It solved thanks for helping.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.