×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to find the ceiling element of the given number in the sorted array

Here, we are going to learn how to find the ceiling element of the given number in the sorted array in C programming language?
Submitted by Nidhi, on July 13, 2021

Problem statement

Given a sorted array arr[] and a number item, the ceiling of the item is the smallest element in array arr[] greater than or equal to item. We have to find the ceiling value of the given number in the sorted array using C program.

Finding ceiling element of given number in a sorted array

The source code to find the ceiling element of the given number in the sorted array is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

C program to find ceiling element of given number in a sorted array

// C program to find Ceiling element of given number in sorted array

#include <stdio.h>

int FindCeilingItem(int arr[], int size, int item)
{
    int index = 0;

    //if first item is greater than or equal to the given item.
    if (item <= arr[0])
        return 0;

    for (index = 0; index < size - 1; index++) {
        if (arr[index] == item)
            return index;

        if (arr[index] < item && arr[index + 1] >= item)
            return index + 1;
    }

    return -1;
}

int main()
{
    int arr[] = { 5, 7, 12, 15, 17, 19, 21 };

    int size = 0;
    int item = 8;
    int index = 0;

    size = sizeof(arr) / sizeof(arr[0]);
    index = FindCeilingItem(arr, size, item);

    if (index == -1)
        printf("Ceiling of item  %d doesn't exist in array\n", item);
    else
        printf("Ceiling of item %d is: %d\n", item, arr[index]);

    return 0;
}

Output

Ceiling of item 8 is: 12

Explanation

Here, we created two functions FindCeilingItem() and main() function. The FindCeilingItem() function is a user-defined function, it is used to find the index of ceiling item of a given number from the given sorted array.

In the main() function, we created an array arr with 7 integer elements. Then we find the ceiling item of the given number item using the FindCeilingItem() function from array arr and then we printed the result on the console screen.

C One-Dimensional Array Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.