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.
/*
* C Program to Find Ceiling & Floor of X given a Sorted Array & a value X
*/
#include <stdio.h>
/* Function to get index of ceiling of x in arr[low..high] */
int ceilSearch(int arr[], int low, int high, int x)
{
int i;
/* If x is smaller than or equal to first element,then return the first element */
if (x <= arr[low])
return low;
/* Otherwise, linearly search for ceil value */
for (i = low; i < high; i++)
{
if (arr[i] == x)
return i;
/* if x lies between arr[i] and arr[i+1] including arr[i+1], then return arr[i+1] */
if (arr[i] < x && arr[i + 1] >= x)
return i + 1;
}
/* If we reach here then x is greater than the last element of the array, return -1 in this case */
return -1;
}
int main()
{
int arr[] = {1, 2, 8, 10, 10, 12, 19};
int n = sizeof(arr)/sizeof(arr[0]);
int x = 3;
int index = ceilSearch(arr, 0, n-1, x);
if (index == -1)
printf("Ceiling of %d doesn't exist in array ", x);
else
printf("ceiling of %d is %d", x, arr[index]);
getchar();
return 0;
}
$ 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!
advertisement
advertisement
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.
Next Steps:
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Buy C Books
- Apply for C Internship
- Buy Computer Science Books