OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in C

Code snippet on how to search for a specific element in an array in C

  int search(int array[], int length, int element) 
    { 
        for (int i = 0; i < length; i++) { 
            if (array[i] == element) 
                return i; 
        } 
        return -1; 
    } 

This code snippet looks for an element in an array and returns its index. To achieve this, it takes three parameters - an array, its length and the element to find in the array. The for loop iterates over the length of the array and compares each element in the array with the element to be found. If a match is found, the function returns the index of that element, else it returns -1. This indicates that the element was not found in the array.

c