-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexercise5.c
44 lines (38 loc) · 928 Bytes
/
exercise5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//documentation section
/* Exercise 5 - Binary Search* by Wong Chin Wee/
//pre-processor section
#include<stdio.h>
//global variable section
//main function section
int main(){
//write here your program
int n,i,a,low,high,mid;
printf("Enter the number of elements: ");
scanf("%d",&n);
int array[n];
printf("Enter the elements in a sorted manner:\n");
for(i=0;i<n;i++)
scanf("%d",&array[i]);
printf("Enter the value to find: ");
scanf("%d",&a);
low=0;
high=n-1;
mid=(low+high)/2;
while(low<=high)
{
if(array[mid]<a)
low=mid+1;
else if(array[mid==a])
{
printf("Element with value %d is present at index %d",a,mid+1);
break;
}
else
high=mid-1;
mid=(low+high)/2;
}
if(low>high)
printf("%d is not present in the array.",a);
return 0;
}
//user-defined section