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[0]);
  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!
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.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.