Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use Pre-defined mathematical function in C language?
In C programming, pre-defined mathematical functions are available in the math.h header file. These functions provide various mathematical operations like power, square root, trigonometric calculations, logarithms, and more. They help perform complex mathematical calculations easily without implementing the logic from scratch.
Syntax
#include <math.h> double function_name(double argument);
Common Mathematical Functions
Here are some commonly used mathematical functions −
| Function | Description | Example |
|---|---|---|
| pow(x, y) | Returns x raised to power y | pow(2, 3) = 8.0 |
| sqrt(x) | Returns square root of x | sqrt(16) = 4.0 |
| cbrt(x) | Returns cube root of x | cbrt(27) = 3.0 |
| ceil(x) | Returns smallest integer ? x | ceil(3.2) = 4.0 |
| floor(x) | Returns largest integer ? x | floor(3.8) = 3.0 |
Example 1: Finding Cube Root Using pow() Function
This example demonstrates how to find the cube root of a number using the pow() function −
#include <stdio.h>
#include <math.h>
int main() {
double number, result;
printf("Enter a number: ");
scanf("%lf", &number);
result = pow(number, 1.0/3.0);
printf("Cube root of %.2lf is: %.2lf
", number, result);
return 0;
}
Enter a number: 27 Cube root of 27.00 is: 3.00
Example 2: Using Ceiling Function
This example shows how to use the ceil() function to round numbers up to the nearest integer −
#include <stdio.h>
#include <math.h>
int main() {
float num1, num2, num3;
printf("Enter 3 numbers: ");
scanf("%f %f %f", &num1, &num2, &num3);
printf("Ceiling of %.1f = %.0f
", num1, ceil(num1));
printf("Ceiling of %.1f = %.0f
", num2, ceil(num2));
printf("Ceiling of %.1f = %.0f
", num3, ceil(num3));
return 0;
}
Enter 3 numbers: 3.7 -4.2 -6.7 Ceiling of 3.7 = 4 Ceiling of -4.2 = -4 Ceiling of -6.7 = -6
Key Points
- Always include
#include <math.h>to use mathematical functions. - Most mathematical functions work with
doubledata type for precision. - When compiling, you may need to link the math library using
-lmflag in some systems. - Mathematical functions return
doublevalues even when input is integer.
Conclusion
Pre-defined mathematical functions in C provide efficient solutions for complex calculations. By including math.h, you can easily perform operations like power, roots, and rounding without implementing custom algorithms.
