V. Altrad V. Altrad - 11 days ago 5
C Question

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

I have a loop that generates random numbers. I want the current iteration of the loop to always remember all the prior iterations and to stop whenever it is equal to any of them.
This is what I have so far, but it only compares the current iteration with the one that comes 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;
}

}

Answer

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;
}