ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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

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

Problem Solution:

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

Program:

The source code to find the floor 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 floor element of given number in sorted array

#include <stdio.h>

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

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

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

    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 = FindFloorItem(arr, size, item);

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

    return 0;
}

Output:

Flooring of item 8 is: 7

Explanation:

Here, we created two functions FindFloorItem() and main() function. The FindFloorItem() function is a user-defined function, it is used to find the index of flooring 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 flooring item of the given number item using the FindFloorItem() function from array arr and then we printed the result on the console screen.

C One-Dimensional Array Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.