The following code shows Implementation of Linear Search and Binary Search in C Language.

C Program to Perform Linear Search

// Linear Search Implementation in C Language


#include <stdio.h>
int LinearSearch(int arr[], int target, int Length)
{
    int i;
    for(i=0;i<Length; i++)
    {
        if (target == arr[i])
            return (i + 1);
    }
    return -1;
}
int main()
{
    int elements_count;
    int n, result;
    //Create an array and initialize it 
    int search_list[] = { 3, 1, 9, 8, 7, 12, 56, 23, 89 };
    elements_count=sizeof(search_list)/sizeof(int);
    
    //Read the target value to search
    printf("Enter a value to search: ");
    scanf("%d", &n);
    result = LinearSearch(search_list, n, elements_count);
    if (n != -1)
        printf("The target value %d is found at position %d", n, result);
    else
        printf("Target not found!");
    return 0;
}

Output

Linear Search in C Language
Linear Search in C Language

C Program to Perform Binary Search

// C Program to Perform Binary Search

#include <stdio.h>
void BubbleSort(int arr[], int Length);
void swap(int arr[], int m, int n);
int search_value(int arr[], int target, int Length)
{
    int low, high, mid;
    low = 0;
    high = Length - 1;
    mid = (low + high) / 2;
    while(low<=high)
    {
        if (arr[mid] == target)
            return mid;
        else
            if (target < arr[mid])
                high = mid - 1;
            else
                low = mid + 1;
        mid = (low + high) / 2;
    }
    return -1;
}
void BubbleSort(int arr[], int Length)
{
    int i, j;
    for(i=0;i<Length-1;i++)
    {
        for(j=0;j<Length-i-1;j++)
        {
            if (arr[j] > arr[j + 1])
                swap(arr, j, j+1);
        }
    }
}
void swap(int arr[], int m, int n)
{
    int t = arr[m];
    arr[m] = arr[n];
    arr[n] = t;
}
int main()
{
    //Create an array and initialize it 
    int search_list[] = { 3, 1, 9, 8, 7, 12, 56, 23, 89 };
    int n, result, i, elements_count;
    elements_count=sizeof(search_list)/sizeof(int);
    //Display the array elements
    printf("Array Elements: ");
    for(i=0;i<elements_count;i++) 
        printf("%d ", search_list[i]);
    printf("\n\n");
    //Sort the array
    BubbleSort(search_list, elements_count);
    printf("Sorted Array: ");
    for(i=0;i<elements_count;i++) 
        printf("%d ", search_list[i]);
    printf("\n\n");
    //Read the target value to search
    printf("Enter a value to search: ");
    scanf("%d", &n);
    result = search_value(search_list, n, elements_count);
    if (result != -1)
        printf("The target value %d is found at position %d", n, (result+1));
    else
        printf("Target not found!");
    return 0;
}

Output

C Program for Binary Search
C Program for Binary Search

Further Reading

50+ C Programming Interview Questions and Answers

C Program to Find Factorial of a Number