Code Scrappers


Linear Search C Program Using Iteration


                    #include<stdio.h>
                    #include<stdlib.h>

                    void linear(int[], int, int);

                    void main()

                    {
                            int i, n, a[10], key;

                            printf("enter the size of the array\n");

                            scanf("%d",&n);

                            printf("enter the array\n");

                            for(i=0;i<n;i++)
                            {
                                    scanf("%d",&a[i]);
                            }

                            printf("enter the element to be searched\n");

                            scanf("%d",&key);

                            linear(a, n, key);

                    }

                    void linear(int a[], int n, int key)

                    {
                            int i, found = 0, pos;

                            for(i=0;i<n;i++)
                            {
                                    if(key == a[i])
                                    {
                                            found++;

                                            pos = i+1;

                                    }
                            }
                            if(found != 0)
                            {
                                    printf("element %d is found at %dth position",key, pos);
                            }

                            else
                            {
                                    printf("element not found\n");
                            }
                    }


                



Output

        enter the no. of elements
        5

        enter the array elements
        1
        4
        7
        5
        2

        enter the elements to be searched
        2

        element 2 is found at 5th position