Algorithms C C++ Tutorials

C Program to search an element in 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
Algorithm to search an element in the array

There are two ways to search element in an array :- 1) Linear Search 2) Binary Search. In this post you’ll be learning linear search.

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

  • Take input for the size and elements of array
  • Input number to search from user in some variable say
  • 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.
  • Run loop from 0 to size. Loop structure should look like for(i=0; i<size; i++).
  • 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.
  • Outside loop if(found == 1) then element is found otherwise not.
#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;
}
Important Notice for college students

If you’re a college student and have skills in programming languages, Want to earn through blogging? Mail us at geekycomail@gmail.com

For more Programming related blogs Visit Us Geekycodes . Follow us on Instagram.

1 comment

Leave a Reply

%d bloggers like this: