C program to search element in an array

Write a C program to read elements in an array and search whether an element exists in the array or not. C program to search an elements in an array linearly. Logic to search an element in the array.



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


Element to search is: 25
Element found at index 3

Required knowledge

Basic C programming, If else, For loop, Array

Logic to search an element in array

There are two searching techniques linear and binary. Here for simplicity I am implementing the linear search algorithm to search an element in a given array. Below is the step by step descriptive logic to search an element in given array.

  1. Input elements in some array, say array contains all elements of array.
  2. Input number to be searched from user, store it in some variable say num.
  3. Define a flag variable as flag = 0. We have initially assumed flag as 0 which means initially we have assumed searched number not found.
  4. Run a loop from 0 to size (where size is the total size of array).
  5. Inside this loop check if array current value is equal to the number or not. Which is if(arr[i] == num) then print element found successfully also make flag = 1 (means value has been found).
  6. Finally after loop check if the flag contains original assigned value or new value. Which is if(flag == 0) then print no elements found.

Program to search an element in array

 * C program to search an element in an array

#include <stdio.h>

int main()
    int arr[100];
    int size, i, num, flag;

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

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

    printf("\nEnter the element to search within the array: ");
    scanf("%d", &num);

    /* Supposes that element is not in the array */
    flag = 0; 
    for(i=0; i<size; i++)
         * If element is found in the array
            flag = 1;
            printf("\n%d is found at position %d", num, i+1);

     * If element is not found in array
        printf("\n%d is not found in the array", num);

    return 0;


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

Enter the element to search within the array: 25

25 is found at position 4

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>