Home > database >  My C program can't find a certain value in an array
My C program can't find a certain value in an array

Time:04-18

My function can't find a specific value in an array. It returns false for value 5 for some reason. This is the function:

int find(const int arr[], int size, int value) {

    for (int i = 0; i < size; i  ) {
        if (arr[i] == value) {
            return i;
        }
        if (value != arr[i]) {
            return -1;
        }
    }
}

Main code:

int main(void) {
    int arr[] = { 4, 1, 5, 3, 6, 3, 1, 9 };

    EQUALS(find(arr, (size)size1, (value)4), 0);      // 4 is at index 0
    EQUALS(find(arr, (size)size1, (value)5), 2);
    EQUALS(find(arr, (size)size1, (value)99), -1);
}

It outputs:

True
False
True

Anyone knows why? I don't understand why it can't find value 5. Thanks!

CodePudding user response:

You should return -1 when you exit the loop without a match (not on the first iteration that doesn't match).

Switch from

for (int i = 0; i < size; i  ) {
    if (arr[i] == value) {
        return i;
    }
    if (value != arr[i]){
        return -1;
    }
}

to

for (int i = 0; i < size; i  ) {
    if (arr[i] == value) {
        return i;
    }
}
return -1;

CodePudding user response:

The if statement within the for loop inside the function

if (value != arr[i]){
    return -1;
}

returns -1 as soon as an element not equal to value is found.

Rewrite the function the following way

int find(const int arr[], int size, int value) 
{
    int i = 0;

    while ( i < size && arr[i] != value )   i;

    return i == size ? -1 : i;
}
  • Related