ceil() Function Example in C Programming

In this source code example, we will see how to use the ceil() function in C programming with an example.

ceil() Function Overview

The ceil() function in C returns the smallest integer value that is not less than the argument. Essentially, it rounds up any decimal number to the nearest whole number. This function is incredibly useful when you want to avoid fractional numbers, such as when calculating the number of items needed or when allocating memory. The function can be found in the math.h library. 

Key Points: 

- Make sure to include the math.h header to access the ceil() function. 

- The function rounds up the decimal number, returning the closest greater integer or the number itself if it's already an integer. 

- Always link the math library using the -lm flag during compilation.

Source Code Example

#include <stdio.h>
#include <math.h>  // Required for ceil()

int main() {
    double value, result;

    // Request input from the user
    printf("Enter a decimal value: ");
    scanf("%lf", &value);

    // Use the ceil() function to round up the value
    result = ceil(value);

    // Display the rounded value
    printf("The ceiling value of %.2lf is: %.0lf\n", value, result);

    return 0;
}

Output

Enter a decimal value: 4.2
The ceiling value of 4.20 is: 5

Explanation

1. We begin by including the essential header files: stdio.h for standard input/output functions and math.h to utilize the ceil() function.

2. In the main() function, the user is asked to input a decimal value.

3. The ceil() function rounds up the entered value to its closest integer.

4. The rounded value is then printed to the console.


Comments