C math.h Library

C Tutorial

C math.h Library

In C math.h Library provides a set of mathematical functions for calculations like exponentiation, logarithms, trigonometry, rounding, and more. It’s widely used in scientific, engineering, and graphics applications.

Note: Always compile with -lm flag in GCC to link the math library.
Example: gcc program.c -o program -lm


📌 Common Math Functions

1️⃣ Basic Arithmetic Functions

FunctionDescription
abs(int x)Returns absolute value of an integer
fabs(double x)Returns absolute value of a floating-point number
fmod(double x, double y)Returns remainder of x/y

Example:


 


2️⃣ Power and Root Functions

FunctionDescription
pow(double x, double y)Returns x raised to the power y
sqrt(double x)Returns square root of x
cbrt(double x)Returns cube root of x

Example:


 


3️⃣ Exponential and Logarithmic Functions

FunctionDescription
exp(double x)Returns e^x
log(double x)Natural logarithm (ln)
log10(double x)Base-10 logarithm

Example:


 


4️⃣ Trigonometric Functions

FunctionDescription
sin(double x)Sine of x (radians)
cos(double x)Cosine of x
tan(double x)Tangent of x
asin(double x)Arcsine (inverse sine)
acos(double x)Arccosine
atan(double x)Arctangent
atan2(double y, double x)Arctangent of y/x with correct quadrant

Example:


 

Note: M_PI is defined in math.h for the value of π.


5️⃣ Rounding and Ceiling/Floor Functions

FunctionDescription
ceil(double x)Returns smallest integer >= x
floor(double x)Returns largest integer <= x
round(double x)Rounds to nearest integer
trunc(double x)Truncates fractional part
fabs(double x)Absolute value (floating-point)

Example:


 


6️⃣ Other Useful Functions

FunctionDescription
hypot(double x, double y)Returns √(x² + y²)
pow10(double x)Returns 10^x (sometimes powl for long double)
fmax(double x, double y)Returns maximum of two numbers
fmin(double x, double y)Returns minimum of two numbers

Example:


 


📌 Summary Table

CategoryFunctions
Absolute Valueabs, fabs
Power & Rootspow, sqrt, cbrt
Log & Explog, log10, exp
Trigonometrysin, cos, tan, asin, acos, atan, atan2
Roundingceil, floor, round, trunc
Miscfmod, hypot, fmax, fmin

✅ Notes

  1. Trigonometric functions use radians, not degrees.

  2. Always compile with -lm to link math library.

  3. For high-precision, use long double versions: powl, sqrtl, etc.

  4. Use fmod instead of % for floating-point remainder.

You may also like...