Search code examples
cmplabxc8

Compare a single integer against an array of integers in C?


How does one compare a single integer to an array of ten integers to find if the single integer is contained within the array using C language? My apologies if original question was unclear, while swipe is equal to any number within the array I want to output PORTD=0b10000000. Thank you!

short a[10]={10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; //Array of accepted passwords.
short array[10];
int i;
for(i=0; i<10; i++){
    array[i]=a[i];
}

srand(clock());

while(1){
int swipe=rand() % 20; /* Simulated code read from card swipe, in this
                        * instance we used a random number between
                        * 1 and 20.*/
for(i=0; i<10; i++){    
    if(swipe == array[i]) {
        PORTD=0b10000000;
    } else {
        PORTD=0b00001000;
    } //If swiped code evaluates as one of the approved codes then set PORTD RD7 as high.
}

char Master=PORTDbits.RD7;

This seems to have solved it...thanks for all of your help!

for(i=0; i<10; i++){    
if(swipe == array[i]) {
    PORTD=0b10000000;
    break;
} else {
    PORTD=0b00001000;
    }
}

Solution

  • In addition to @kaylum's answer...

    Because you are calling rand() in a loop, you need to call srand() first before entering the loop,

    srand(clock());//for example
    while(1){
        LATD=0x00;
        int swipe=rand() % 20;
        ...   
    

    If you do not, the random numbers you get will be the same sequence of values every time you execute.

    Additionally, if i is not reinitialized before being used to compare, it is == 10. It needs to be reset before using as your array index...

    Also, in your code, it appears you want to check the latest random number against the 10 accepted passwords. If that is correct, you must compare all 10 of them:

    int main(void)
    {
        srand(clock());//for example
        j = 0;
        while(1)
        {
            int swipe=rand() % 20;
            PORTD=0b00000000;
            for(i=0;i<10;i++)
            {
                j++;
                if(swipe == array[i]) 
                {
                    PORTD=0b10000000;
                    break;
                } 
    
            }
            //to show ratio of legal to illegal passcodes...
            printf("times through: %d  Value of PORTD %d\n", j, PORTD);
        }
    }