C Math Functions

C Tutorial

C Math Functions

C provides powerful mathematical functions through the math library
Header file: <math.h>

These functions are widely used in:

  • Scientific calculations

  • Engineering programs

  • Graphics

  • Embedded systems

  • Competitive programming


 How to Use Math Functions in C

Include Header File

#include <math.h>

Compile with Math Library (Important)

gcc program.c -lm

(-lm links the math library)


 Common Math Functions (Most Used)

sqrt() – Square Root


pow() – Power


abs() – Absolute Value (int)


fabs() – Absolute Value (float/double)


 Trigonometric Functions

(All angles are in radians)

FunctionDescription
sin(x)Sine
cos(x)Cosine
tan(x)Tangent
asin(x)Inverse sine
acos(x)Inverse cosine
atan(x)Inverse tangent

Example


 


 Logarithmic & Exponential Functions

FunctionMeaning
log(x)Natural log (ln)
log10(x)Base-10 log
exp(x)

Example


 Rounding Functions

FunctionDescription
ceil(x)Round up
floor(x)Round down
round(x)Nearest integer
trunc(x)Remove decimal

Example


 Min / Max & Remainder

fmod() – Floating Modulus


 Integer Math vs Floating Math

  •  Use floating-point values to get correct results

 Math Constants (Using Macros)

(Some compilers also support M_PI, but not standard)


 Complete Example Program


 


Common Mistakes

  •  Forgetting #include <math.h>
  •  Not using -lm during compilation
  •  Using abs() for floating values
  •  Using degrees instead of radians

 Interview Questions (Very Important)

  1. Which header file contains math functions?

  2. Difference between abs() and fabs()?

  3. Why -lm is required?

  4. Difference between ceil() and floor()?

  5. pow() return type?


 Real-Life Use Cases

  • Engineering calculations

  • Signal processing

  • 3D graphics

  • Embedded sensors

  • Financial software


 Summary

  •  Math functions are defined in <math.h>
  •  Use -lm while compiling
  •  Trigonometric functions use radians
  •  Essential for placements & projects

You may also like...