Page 265 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 265

Fundamentals of Data Structures




                    Notes

                                     Case Study  Using Recursive and Non-recursive Functions
                                                 to Perform Searching Operations


                                     Write C programs that use both recursive and non-recursive functions to perform the
                                     following searching operations for a Key value in a given list of integers: (i) Linear search,
                                     (ii) Binary search
                                     /* C program linear search using non-recursive functions*/
                                     #include<stdio.h>
                                     #include<conio.h>
                                     main()
                                     {
                                         int a[100],i,n,ele,loc=-1;
                                         clrscr();
                                         printf("Enter Size");
                                         scanf("%d",&n);
                                         printf("Enter %d elements",n);
                                         for(i=0;i<n;i++)
                                         scanf("%d",&a[i]);
                                         printf("The array elements");
                                         for(i=0;i<n;i++)
                                         printf("%4d",a[i]);
                                         printf("\nEnter element to search");
                                         scanf("%d",&ele);
                                         for(i=0;i<=n-1;i++)
                                         {
                                           if(ele==a[i])
                                           {
                                             loc=i;
                                             break;
                                           }
                                         }
                                         if(loc>=0)
                                         printf("\nThe element %d found at %d location",ele,loc+1);
                                         else
                                         printf("\nThe element %d is not found",ele);
                                         getch();
                                     }
                                     int lin_search(int x[100],int n,int ele)
                                     {

                                                                                                         Contd...



          258                               LOVELY PROFESSIONAL UNIVERSITY
   260   261   262   263   264   265   266   267   268   269   270