Code Scrappers


Searching an element in an array C program


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

            void main()
            {
                int a[10], n, key, found=0, i, pos;

                printf("enter the size of 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);

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

                        found++;

                        pos = i+1;
                    }
                }

                if(found == 0)
                {
                    printf("element not found");
                }

                else
                {
                    printf("Element %d is found at %dth position",key, pos);
                }
            }


          



Output

      enter the size of array
      5

      enter the array
      5
      2
      1
      7
      8

      enter the element to be searched
      1

      Element 1 is found at 3th position