V. Altrad
V. Altrad

Reputation: 3

C - Comparing an element in an array with all the previous ones

I have a loop that generates random numbers. I want to compare the random number generated in the current iteration with random numbers generated in all the previous iterations and break when there is match between two random numbers. This is what I have so far, but it only compares the current random number with the one that is generated right before it.

for (i = 0; i < SIZE; ++i)
{
    a[i] = (100*(1 + rand() % 12)) + (1 + rand() % 30);

    for (j = i - 1; j < SIZE; ++j)
    {
        if (a[i] != a[j])
        {
            printf("Person %i - %i\n", i, a[i]);
        }
        else break; 
    }

}

Upvotes: 0

Views: 71

Answers (1)

Tesseract
Tesseract

Reputation: 8139

Is this what you had in mind?

for (i = 0; i < SIZE; ++i)
{
    a[i] = (100*(1 + rand() % 12)) + (1 + rand() % 30);
    found = 0;
    for (j = 0; j < i; ++j)
    {
        if (a[i] == a[j])
        {
             found = 1;
             break;
        }
    }
    if(!found) 
    {
        printf("Person %i - %i\n", i, a[i]);
    }
    else
        break;
}

Upvotes: 1

Related Questions