Wednesday, 24 September 2014

Search an element in array

As we know an array can store more than one element.  In programming you may have to search that element in array. and then do some important operation.
Let’s write the program
#include<stdio.h>
#include<conio.h>
int arr[100],i,p=1,length;
int search(int);
int display(int);
void main()
{

    printf("enter the length of the arry:(<=100)");
    scanf("%d",&length);
    if(length<=100)
    {
    printf("length successfully entered.And the legth is:%d \n",length);
    }
    else
    {
    printf("length is invalid.\n");
    main();
    }
    length--;
    printf("Enter the elments of the array:\n");
    for(i=0;i<=length;i++)
    {
        printf("\n%d position's:",p++);
        scanf("%d",&arr[i]);
    }
    display(length);
search(length);

   getch();
}
int display(int length)
{
    printf("\nNow the array is:\n");
    for(i=0;i<=length;i++)
    {
        printf("%d\t",arr[i]);
    }
}
int search(int length)
{
   int c, first, last, middle, n, search;

    n=length;
    printf("\nEnter value to find\n");
    scanf("%d",&search);

    first = 0;
    last = n;
    middle = (first+last)/2;

    while( first <= last )
    {
        if ( arr[middle] < search )
        first = middle + 1;
        else if ( arr[middle] == search )
        {
            printf("%d found at location %d.\n", search, middle+1);
            break;
        }
        else
            last = middle - 1;

            middle = (first + last)/2;
    }
    if ( first > last )
    printf("Not found! %d is not present in the list.\n", search);

   return 0;
}
In above program we take an array and put element in it. Then we search for an element which is already in that array. If given element does not match with any element in array then it will show not found.
Now let’s see output
enter the length of the arry:(<=100)5
length successfully entered.And the legth is:5
Enter the elments of the array:
1 position's: 65
2 position's: 55
3 position's: 41
4 position's: 33
5 position's: 87
Now the array is:
65 55 41 33 87
Enter value to find 41
41 found at location 3

0 comments:

Post a Comment