1|Page
ARRAY Q. To search an element from an array using non-recursive function. Ans. Program in language C: /*********Binary Search using non-recursive function*********/ #include #include<stdio.h> /************************************************************/ void binary_search(int arr[], int start, int end, int n) { int mid; while(start<=end) { mid=(start+end)/2; if(arr[mid]==n) { printf("\nElement found in position %d", mid+1); getch(); return; } if(arr[mid]n) end=mid-1; } printf("\nElement not found"); getch(); } /*************************************************************/ void main() { int ar[10], ele, i, n; clrscr(); printf("\nEnter number of elements in the array: "); scanf("%d",&n); printf("\nEnter the elements in the array:\n"); for(i=0;i
2|Page
Output of the program in C:
Q. To search an element from an array using recursive function. Program in language C: /******** Binary Search using recursive function*********/ #include #include<stdio.h> /********************************************************/ void binary_search(int arr[], int start, int end, int n) { int mid; mid=(start+end)/2; if(arr[mid]==n) printf("\nElement found in position %d of the array.",mid+1); if(arr[mid]n) binary_search(arr, start, mid-1, n); } /*********************************************************/ void main() { int ar[50], ele, i, n; clrscr(); printf("\nEnter number of elements in the array: "); scanf("%d",&n); printf("\nEnter the elements in the array:\n"); for(i=0;i
3|Page scanf("%d",&ar[i]); } printf("\nEnter the element to be searched:"); scanf("%d",&ele); binary_search(ar,0,n-1,ele); getch(); } /*********************************************************/ Output of the program in C: