Monday, February 26, 2018

Linear search program in C using array

Linear/Sequential Search program in C


#include <stdio.h>

int linear (int a[], int tot_keys, int k);
int main()
    int a[50];
    int n,i,key;
    int flag=0, found_at;
    //Reading input
    printf ("\n Enter the number of elements : ");
    scanf ("%d", &n);

    for(i=0; i<n; i++)   //to read list of keys
           printf("\n Enter the key %d:", i);
           scanf("%d", &a[i]);
    printf("\nEnter the data to be searched for:");
    scanf("%d", &key);
//following line calls the function linear with the parameters array of keys (a), total //keys (n) in the array, and the key (key) to be searched. The result returned by the //function stored in variable ‘found_at’.
    found_at = linear(a, n, key);
       printf("\nData is present at position %d", found_at);
       printf("\nData not present");
int linear(int a[], int tot_keys, int k)
    int i, position = -1;
    for(i=0; i < tot_keys; i++) //this loop executes the number of keys time
       if(a[i]==k) //checks if the key at position i is equal to key to be searched
          position = i; //we remember the position of key in array
    return position;


Linear search program in C
Sequential search program in C

No comments:

Post a Comment

Featured Content

Multiple choice questions in Natural Language Processing Home

MCQ in Natural Language Processing, Quiz questions with answers in NLP, Top interview questions in NLP with answers Multiple Choice Que...

All time most popular contents

data recovery