Friday, 5 October 2018

Linear Search with Pointer

 

C Code 


#include<stdio.h>
#include<stdlib.h>            //for using malloc function
int c=0;                         // for search function 0 means element not found
int linearsearch(int *, int,int);     // Prototype of function
int main()
{
    int *a,i,n,key; //define *a as a pointer of array
    printf("Enter the size of an array: ");
    scanf("%d",&n);
    a=(int*)malloc(n*sizeof(int));          //allocate memory to store element in array
    printf("Enter the elements of the array: ");
    for(i=0;i<=n-1;i++)
    {
         scanf("%d",(a+i));           // Scan array with pointer of array starting from 1st location
    }

    printf("Enter the number to be search: ");
    scanf("%d",&key);
    i=0;
    i=linearsearch(a,key,n);
     
    if(c==0)
         printf("The number is not in the list\n");
    else
         printf("The number is found at position %d\n",i+1);

    return 0;
}

int linearsearch(int *a,int b,int  n)

{
    int i;
for(i=0;i<=n-1;i++)
    {
         if(*(a+i)==b)  // Condition check with pointer
       {
             c=1; // Set C to 1 when element found
             break;
         }
    }
    return i; //return value of i as it indicate position of key found
}

/* Output
Enter the size of an array:10
Enter the element of an array: 10 20 30 40 50 60 70 80 90 100
Enter the number to be search :70
The number is found at position 7
*/


No comments:

Post a Comment