Answer to Question #198811 in C++ for adil

Question #198811

Take a sorted array of 15 elements of type int and a value x from user, you need to find the ceiling

and floor of 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 than the array is sorted in

ascending order. Write functions to find floor and ceiling of x from the given array.


1
Expert's answer
2021-05-27T19:11:10-0400
#include <iostream>

bool GetCeiling(int* data, int size, int x, int* ceiling)
{
    if(x <= data[0])
    {
        *ceiling = data[0];
        return true;
    }
    
    for(int i=0; i<size-2; ++i)
    {
        if(data[i] == x)
        {
            *ceiling = x;
            return true;
        }

        if(data[i] < x && x <= data[i + 1])
        {
            *ceiling = data[i + 1];
            return true;
        }
    }

    return false;
}

bool GetFloor(int* data, int size, int x, int* floor)
{
    if(data[size - 1] <= x)
    {
        *floor = data[size - 1];
        return true;
    }

    for(int i=size-1; i>0; --i)
    {
        if(data[i] == x)
        {
            *floor = x;
            return true;
        }

        if(data[i - 1] <= x && x < data[i])
        {
            *floor = data[i - 1];
            return true;            
        }
    }

    return false;
}

int main()
{
    const int ARRAY_SIZE = 15;
    int data[ARRAY_SIZE];
    
    std::cout << "Please enter sorted array of " << ARRAY_SIZE <<" integers: ";
    
    for(int i=0; i<ARRAY_SIZE; ++i)
    {
        std::cin >>data[i];

            if(!std::cin)
            {
                std::cout << "Bad input\n";
                return 1;
            }
    }
    
    int x;
    std::cout << "Please enter value: ";
    std::cin >>x;

        if(!std::cin)
        {
            std::cout << "Bad input\n";
            return 1;
        }   

    int ceiling;
    if(!GetCeiling(data, ARRAY_SIZE, x, &ceiling))
    {
        std::cout << "Ceiling does not exist\n";
    }
    else
    {
        std::cout << "Ceiling is " << ceiling << "\n";
    }

    int floor;
    if(!GetFloor(data, ARRAY_SIZE, x, &floor))
    {
        std::cout << "Floor does not exist\n";
    }
    else
    {
        std::cout << "Floor is " << floor << "\n";
    }
    
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog