Monday, 26 February 2018

Linear search program in C using array

Linear/Sequential Search program in C


Program:

#include <stdio.h>
#include<conio.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);
   
    //Searching...
//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);
    if(found_at!=-1)
       printf("\nData is present at position %d", found_at);
    else
       printf("\nData not present");
    getch();
}
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

SQL exercises for beginners one

SQL Exercises for Beginners / Simple SQL Exercises with Answers / Solved SQL exercises / SQL solved exercises with simple conditions / So...