# C Program to Find Ceiling and Floor Value of Sorted Array

«
»
This C Program calculates ceiling & floor of X given a sorted array & a value X.

Here is source code of the C Program to calculate ceiling & floor of X given a sorted array & a value X. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

1. `/*`
2. ` * C Program to Find Ceiling & Floor of  X given a Sorted Array & a value X`
3. ` */`
4. ` #include <stdio.h>`
5. ` `
6. `/* Function to get index of ceiling of x in arr[low..high] */`
7. `int ceilSearch(int arr[], int low, int high, int x)`
8. `{`
9. `     int i;`
10. ` `
11. `    /* If x is smaller than or equal to first element,then return the first element */`
12. `    if (x <= arr[low])`
13. `    return low;`
14. ` `
15. `   /* Otherwise, linearly search for ceil value */`
16. `   for (i = low; i < high; i++)`
17. `   {`
18. `       if (arr[i] == x)`
19. `          return i;`
20. ` `
21. `       /* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */`
22. `       if (arr[i] < x && arr[i + 1] >= x)`
23. `           return i + 1;`
24. `   }`
25. ` `
26. `   /* If we reach here then x is greater than the last element of the array,  return -1 in this case */`
27. `   return -1;`
28. `}`
29. ` `
30. `int main()`
31. `{`
32. `    int arr[] = {1, 2, 8, 10, 10, 12, 19};`
33. `    int n = sizeof(arr)/sizeof(arr);`
34. `    int x = 3;`
35. `    int index = ceilSearch(arr, 0, n-1, x);`
36. `    if (index == -1)`
37. `        printf("Ceiling of %d doesn't exist in array ", x);`
38. `    else`
39. `        printf("ceiling of %d is %d", x, arr[index]);`
40. `    getchar();`
41. `    return 0;`
42. `}`

```\$ cc pgm99.c
\$ a.out
ceiling of 3 is 8```

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Arrays, go to C Programming Examples on Arrays. If you wish to look at programming examples on all topics, go to C Programming Examples. 