Given a sorted array and a value x, the ceiling of x is the smallest element in array greater than or equal to x, and the floor is the greatest element smaller than or equal to x. Assume that the array is sorted in non-decreasing order. Write a program to find floor and ceiling of x. 
Example: 
Let the input array be {1, 2, 8, 10, 10, 12, and 19} 
For x = 0:    Floor does not exist in array, Ceil = 1 
For x = 1:    Floor = 1, Ceil = 1 
For x = 5:    Floor = 2, Ceil = 8 
For x = 20:  Floor = 19, Ceil does not exist in array 

Assume: The array elements are positive. 

Input Format: 
The first line of the input consists of an integer, n that corresponds to the number of elements in an array. 
The next ‘n’ lines in the input correspond to the elements in an array. 
The next line of the input consists of an integer, x. 

Output Format: 
The output is an integer. 
Refer sample input and output for formatting specifications. 

Sample Input1: 
10 
10 
12 
19 
Sample Output1: 
Floor = 2 
Ceil = 8 
  
Sample Input2: 
10 
10 
12 
19 
Sample Output2: 
Floor does not exist in array 
Ceil = 1 


Program Code:
#include <stdio.h>
 #include<stdlib.h>
void floorAndCeil(int arr[], int n, int x)
{
    int fInd, cInd;
    int i;
    int fDist = 32767, cDist = 32767;
    for (i=0; i<n; i++)
    {
        if (arr[i] >= x && cDist > (arr[i] - x))
        {
           cInd = i;
           cDist = arr[i] - x;
        }
        if (arr[i] <= x && fDist > (x - arr[i]))
        {
           fInd = i;
           fDist = x - arr[i];
        }
    }

    if (fDist == 32767)
      printf("Floor does not exist in array\n");
    else
      printf("Floor = %d\n",arr[fInd]);
    if (cDist == 32767)
      printf("Ceil does not exist in array\n");
    else
      printf("Ceil = %d",arr[cInd]);
}

int main()
{
    int a[100], i, n,x;
    scanf("%d", &n);
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    scanf("%d", &x);
    floorAndCeil(a, n, x);
    return 0;
}
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: