0

I want to do generate 7 different number (0-9) - first digit should not be 0- and put them into an array. Every number should be unique. I know what I did wrong but I dont know what should I do.

int arr[7], j, i;
    srand(time(NULL));
    for (i = 0; i < 7; i++)
    {
        arr[i] = rand() % 10;
                if (arr[0] == 0) 
                arr[0] = rand() % 10;
}
    for (i = 0; i < 7; i++)
    {
        for (j = 0; j < 7; j++)
        {
            
            if (i == j) {
                j++;
            }
            if (arr[i] == arr[j])
                arr[j] = rand() % 10;
    
        
        }
    }
    printf("\n");
    for(j=0;j<7;j++)
            printf("\n%d ", arr[j]);
sourab maity
  • 1,025
  • 2
  • 8
  • 16
  • 1
    Does this answer your question? [Random and Different Numbers in C](https://stackoverflow.com/questions/65594440/random-and-different-numbers-in-c) – Damien Jan 06 '21 at 16:03
  • I would go with generating a random *permutation* of digits 0-9, then pick the first 8. If first one is zero, will pick staring from the second. Not sure how not having `0` as first digit (and having as any of the others) aligns with *any* lottery rules though. – Eugene Sh. Jan 06 '21 at 16:04
  • Strange, a very exact duplicate 5 hours ago ! – Damien Jan 06 '21 at 16:04

1 Answers1

0
  • You can use rand() % 9 + 1 to produce random number between 1 and 9.
  • arr[j] may be out-of-range after j++;.

Try this:

int arr[7], j, i;
srand(time(NULL));
arr[0] = rand() % 9 + 1; /* decide first number with special formula */
for (i = 1; i < 7; i++) /* decide the rest numbers */
{
    int dupe = 0;
    arr[i] = rand() % 10;
    for (j = 0; j < i; j++) /* check against numbers that already decided */
    {
        if (arr[i] == arr[j])
            dupe = 1; /* ouch, this number is already used! */
    }
    if (dupe)
        i--; /* if the number is already used, try again */
}
printf("\n");
for(j=0;j<7;j++)
    printf("\n%d ", arr[j]);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70