C library - ceil() function



The C library ceil() function of type double accept the single argument(x) that returns the smallest integer value greater than or equal to, by the given value.

This method rounded up the nearest integer.

Syntax

Following is the syntax of the C library function ceil()

double ceil(double x)

Parameters

This function accepts only a single parameter −

  • x − This is the floating point value.

Return Value

This function returns the smallest integral value not less than x.

Example 1

The C library program illustrates the usage of ceil() function.

#include <stdio.h>
#include <math.h>

int main () {
   float val1, val2, val3, val4;

   val1 = 1.6;
   val2 = 1.2;
   val3 = 2.8;
   val4 = 2.3;

   printf ("value1 = %.1lf\n", ceil(val1));
   printf ("value2 = %.1lf\n", ceil(val2));
   printf ("value3 = %.1lf\n", ceil(val3));
   printf ("value4 = %.1lf\n", ceil(val4));
   
   return(0);
}

Output

On execution of above code, we get the following result −

value1 = 2.0
value2 = 2.0
value3 = 3.0
value4 = 3.0

Example 2

Below the program generates a table of ceiling integers for a range of positive floating-point numbers.

#include <stdio.h>
#include <math.h>

int main() {
   double start = 1.5;
   double end = 10.5;

   printf("Table of Ceiling Integers:\n");
   for (double num = start; num <= end; num += 1.0) {
       int result = ceil(num);
       printf("Ceil(%.2lf) = %d\n", num, result);
   }

   return 0;
}

Output

After executing the code, we get the following result −

Table of Ceiling Integers:
Ceil(1.50) = 2
Ceil(2.50) = 3
Ceil(3.50) = 4
Ceil(4.50) = 5
Ceil(5.50) = 6
Ceil(6.50) = 7
Ceil(7.50) = 8
Ceil(8.50) = 9
Ceil(9.50) = 10
Ceil(10.50) = 11

Example 3

In this program, we round up the given value into rounded floating point value.

#include <stdio.h>
#include <math.h>

int main() {
   double num = 8.33;
   int result = ceil(num);

   printf("Ceiling integer of %.2lf = %d\n", num, result);
   return 0;
}

Output

The above code produces the following result −

Ceiling integer of 8.33 = 9
Advertisements