Home » Code Snippets » C/C++ Data Structure programs

Linear/ Sequential Searching Data Structure Example in C - C program to find an element using Linear/Sequential Searching from an Array.

Linear or Sequential searching algorithm is used to find the item in a list, This algorithm consist the checking every item in the list until the desired (required) item is found.
This searching algorithm is very simple to use and understand.

Linear/Sequential Searching Implementation using C program



/*
    program to implement Linear Searching,
    to find an element in array.
*/
 
#include <stdio.h>
 
#define MAX 5
 
/**     function    :   linearSearch()
    to search an element.
**/
int linearSearch(int *a,int n)
{
    int i,pos=-1;
 
    for(i=0;i< MAX; i++)
    {
        if(a[i]==n)
        {
            pos=i;
            break;
        }
    }
    return pos;
}
 
int main()
{
    int i,n,arr[MAX];
    int num;     /* element to search*/
    int position;
 
    printf("\nEnter array elements:\n");
    for(i=0;i< MAX;i++)
        scanf("%d",&arr[i]);
 
    printf("\nNow enter element to search :");
    scanf("%d",&num);
 
    /* calling linearSearch function*/
 
    position=linearSearch(arr,num);
 
    if(num==-1)
        printf("Element not found.\n");
    else
        printf("Element found @ %d position.\n",position);
 
    return 0;
}

Output

    Enter array elements:
    10
    20
    15
    30
    40

    Now enter element to search :15
    Element found @ 2 position. 





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.