C program to search element in an array

Write a C program to input elements in array and search whether an element exists in array or not. How to search element in array linearly in C programming. Logic to search element in array sequentially in C program.

Example

Input

Input size of array: 10
Input elements in array: 10, 12, 20, 25, 13, 10, 9, 40, 60, 5

Output

Element to search is: 25
Element found at index 3

Required knowledge

Basic Input Output, If else, For loop, Array

Logic to search element in array

There are two searching techniques linear and binary. For simplicity, I am implementing linear search algorithm to search element in array.

Step by step descriptive logic to search element in array using linear search algorithm.

  1. Input size and elements in array from user. Store it in some variable say size and arr.
  2. Input number to search from user in some variable say toSearch.
  3. Define a flag variable as found = 0. I have initialized found with 0, which means initially I have assumed that searched element does not exists in array.
  4. Run loop from 0 to size. Loop structure should look like for(i=0; i<size; i++).
  5. Inside loop check if current array element is equal to searched number or not. Which is if(arr[i] == toSearch) then set found = 1 flag and terminate from loop. Since element is found no need to continue further.
  6. Outside loop if(found == 1) then element is found otherwise not.

Program to search element in array

/**
 * C program to search element in array
 */

#include <stdio.h>

#define MAX_SIZE 100  // Maximum array size

int main()
{
    int arr[MAX_SIZE];
    int size, i, toSearch, found;

    /* Input size of array */
    printf("Enter size of array: ");
    scanf("%d", &size);

    /* Input elements of array */
    printf("Enter elements in array: ");
    for(i=0; i<size; i++)
    {
        scanf("%d", &arr[i]);
    }

    printf("\nEnter element to search: ");
    scanf("%d", &toSearch);

    /* Assume that element does not exists in array */
    found = 0; 
    
    for(i=0; i<size; i++)
    {
        /* 
         * If element is found in array then raise found flag
         * and terminate from loop.
         */
        if(arr[i] == toSearch)
        {
            found = 1;
            break;
        }
    }

    /*
     * If element is not found in array
     */
    if(found == 1)
    {
        printf("\n%d is found at position %d", toSearch, i + 1);
    }
    else
    {
        printf("\n%d is not found in the array", toSearch);
    }

    return 0;
}

Learn more how to search an element in array using pointer.

Output

Enter size of array: 10
Enter elements in array: 10 12 20 25 13 10 9 40 60 5

Enter element to search: 25

25 is found at position 4

Happy coding 😉