Monday, 10 March 2014

Write the following function: int search(int a[], int n, int x); Where a is an array to be searched, n is the number of elements in the array, and x is the search key. “search” should return 1 if x matches some element of a, 0 if it doesn’t. Use pointer arithmetic to visit array elements. Include appropriate documentation in your program.

#include<stdio.h>

int search(int a[],int n,int x);

main()
{
    int a[100],i,n,ele,f;
    printf("\nEnter how many terms=");
    scanf("%d",&n);
    printf("\nEnter the elements=");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("\nThe elements are=");
    for(i=0;i<n;i++)
    {
        printf("%d ",*(a+i));
    }
    printf("\nEnter the element to be searched=");
    scanf("%d",&ele);
    f=search(a,n,ele);
    if(f==-1)
        printf("\nElement not found");
    else
        printf("\nElement found in position %d",f);
}

int search(int a[],int n,int x)
{
    int i,f=0;
    for(i=0;i<n;i++)
    {
        if(a[i]==x)
        {
            return 1;
        }
    }
    return 0;
}

No comments:

Post a Comment