Linear Search And Binary Search With Goto Function In C

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

void lin();
void bin();

int main(){
	int digit;
	label : 
	printf("\nFor Linear Search Press : 1 \n");
	printf("For Binary Search (Sequensial) Press : 2\n");
	printf("For Exit Press : 3\n");
	printf("Please Enter Your Desier Option : \t");
	scanf("%d",&digit);
	switch(digit){
		case 1:
			lin();
			goto label;
		case 2: 
			bin();
			goto label;
		case 3: 
			exit(0);
	}
	
}


void lin()
 {
   int arr[100], src, i, num, loc;
   printf("Enter the number of elements in array : \n");
   scanf("%d",&num);
   printf("Enter %d numbers.\n", num);
   for(i=0;i<num;i++){
		printf("Data %d = ",i+1);
		scanf("%d",&arr[i]);
	}
   printf("Enter the number to search\n");
   scanf("%d",&src);
   for ( i = 0 ; i < num ; i++ )
   {
     if ( arr[i] == src )  
     {
     	loc=i+1;
       printf("%d is present at location %d.\n", src,loc);
       break;
     }
}
    if(i==num)
     printf("%d is not present in array.\n", src);
 }
 
void bin()
    {
       int i, first, last, middle, n, search, array[100];
     
       printf("Enter number of elements : \n");
       scanf("%d",&n);
  
       printf("Enter %d integers : \n", n);
     
       for (i = 0; i < n; i++)
          scanf("%d",&array[i]);
     
       printf("Enter value to find : \n");
       scanf("%d", &search);
     
       first = 0;
       last = n - 1;
       middle = (last)/2;
     
       while (first <= last) {
          if (array[middle] < search)
             first = middle + 1;    
          else if (array[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 isn't present in the list.\n", search);
       
    }

Hits: 13

S M Mohaimanul Islam

Mad man loving technology.

Leave a Reply

Your email address will not be published. Required fields are marked *