Back to C Programming
2025-12-037 min read

Common mathematical functions

Learn Common mathematical functions step by step with clear examples and exercises.

Title: A full guide to Common Mathematical Functions in C Programming

Why This Matters

Understanding common mathematical functions is essential for any C programmer as they serve as fundamental building blocks for solving a wide array of problems, ranging from simple arithmetic to complex calculations involving trigonometry and exponents. Mastering these functions will make you more efficient and effective in your programming tasks.

Prerequisites

Before delving into the world of mathematical functions, it's essential to have a strong grasp of:

  1. Basic C syntax and control structures (if, for, while)
  2. Variables and data types
  3. Functions and function prototypes
  4. Input/Output operations (scanf, printf)
  5. Understanding of floating-point numbers and their importance in mathematical calculations
  6. Familiarity with the C standard library header files such as ` and `

Core Concept

Basic Operations

C provides several functions to perform basic mathematical operations such as addition, subtraction, multiplication, and division. These functions ensure that the results are always accurate and avoid potential issues with integer division.

#include <stdio.h>

int main() {
int a = 10;
int b = 20;
int sum = a + b; // addition
int diff = a - b; // subtraction
int prod = a * b; // multiplication
float div_result = (float)a / b; // division
printf("Sum: %d\n", sum);
printf("Difference: %d\n", diff);
printf("Product: %d\n", prod);
printf("Quotient: %.2f\n", div_result);
return 0;
}

In this example, we declare two integer variables a and b, perform basic mathematical operations on them, and print the results. Note that we had to cast one of the operands to a floating-point type when performing division to avoid integer division.

Absolute Value, Maximum, Minimum, and Remainder

C offers functions like abs(), fabs(), labs(), llabs(), imaxabs(), fmax(), fmin(), fdim(), and remquo() to handle absolute values, maximums, minimums, and remainders.

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

int main() {
int num = -20;
float abs_num = abs(num); // absolute value
float fabs_num = fabs((float)num); // floating-point absolute value
int max_num = imaxabs(num, 10); // maximum of two values (integer)
float max_num_f = fmax(num, 10.5f); // maximum of two values (floating-point)
printf("Absolute Value: %.2f\n", abs_num);
printf("Floating-Point Absolute Value: %.2f\n", fabs_num);
printf("Maximum (integer): %d\n", max_num);
printf("Maximum (float): %.2f\n", max_num_f);
return 0;
}

In this example, we demonstrate how to use various functions for absolute values, maximums, and minimums.

Exponential Functions

C provides functions like exp(), exp10(), exp2(), expm1(), log(), log10(), log2(), log1p(), and log2p1() for exponential and logarithmic calculations.

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

int main() {
float base = 2.5;
float exp_result = exp(base); // e^x
float ten_exp_result = exp10(base); // 10^x
float two_exp_result = exp2(base); // 2^x
float expm1_result = expm1(base); // e^x - 1
printf("e^2.5: %.2f\n", exp_result);
printf("10^2.5: %.2f\n", ten_exp_result);
printf("2^2.5: %.2f\n", two_exp_result);
printf("e^2.5 - 1: %.2f\n", expm1_result);
return 0;
}

In this example, we showcase the use of exponential and logarithmic functions in C.

Trigonometric Functions

C offers functions like sin(), cos(), tan(), asin(), acos(), atan(), atan2(), sinh(), cosh(), tanh(), and many more for trigonometry.

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

int main() {
float angle = 30 * M_PI / 180; // 30 degrees in radians
float sin_result = sin(angle); // sine of an angle
float cos_result = cos(angle); // cosine of an angle
float tan_result = tan(angle); // tangent of an angle
printf("Sine: %.2f\n", sin_result);
printf("Cosine: %.2f\n", cos_result);
printf("Tangent: %.2f\n", tan_result);
return 0;
}

In this example, we demonstrate the use of trigonometric functions in C.

Worked Example

... (Include a detailed worked example with line-by-line explanations)

Common Mistakes

  1. Forgetting to include the header file `` for mathematical functions.
  2. Using integer division without casting at least one operand to a floating-point type when performing division.
  3. Not handling edge cases, such as dividing by zero or taking the absolute value of a negative number with an unsigned data type.
  4. Incorrectly using trigonometric functions with angles outside the valid range (0 to 2π).
  5. Mixing floating-point and integer arithmetic without proper casting.
  6. Neglecting to initialize variables before using them in calculations.
  7. Failing to check for errors or invalid inputs when using mathematical functions.

Subheadings under Common Mistakes:

1.1. Integer Division Pitfalls

1.2. Edge Cases and Valid Angle Ranges

1.3. Mixed Arithmetic and Casting Errors

1.4. Uninitialized Variables and Null Pointer Dereferencing

1.5. Error Handling and Input Validation

Practice Questions

  1. Write a program that calculates the area of a circle given its radius.
  2. Write a program that finds the larger of two numbers using fmax() function.
  3. Write a program that checks if a number is positive, negative, or zero using mathematical functions.
  4. Write a program that converts degrees to radians and vice versa.
  5. Write a program that calculates the square root of a given number using the sqrt() function.
  6. Write a program that finds the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
  7. Write a program that calculates the factorial of a given number recursively.
  8. Write a program that solves a quadratic equation ax^2 + bx + c = 0 using the quadratic formula.
  9. Write a program that calculates the derivative of a polynomial function using finite differences.
  10. Write a program that generates a random number between two given values and prints its factorization.

FAQ

Q: Why do I need to cast at least one operand when performing division in C?

A: To avoid integer division, which rounds down the result towards zero, you should cast at least one operand to a floating-point type (e.g., float or double). This ensures that the result is a floating-point number with decimal precision.

Q: What's the difference between fabs() and abs() in C?

A: fabs() calculates the absolute value of a floating-point number, while abs() calculates the absolute value of an integer number. If you need to find the absolute value of a floating-point number that is already declared as an integer, you should cast it to a floating-point type before calling fabs().

Q: Why can't I use trigonometric functions with angles outside the range (0 to 2π)?

A: Trigonometric functions in C expect their arguments to be in radians, which range from 0 to 2π. If you provide an angle outside this range, the results may not be accurate or undefined. To avoid this issue, always convert angles to radians before using trigonometric functions.

Q: Why do I get a compilation error when trying to use mathematical functions without including ``?

A: The header file `` declares all the mathematical functions in C, so you must include it at the beginning of your program to use any mathematical function.

Q: Why does my program return incorrect results when mixing floating-point and integer arithmetic without proper casting?

A: When mixing floating-point and integer arithmetic without proper casting, the compiler performs implicit type conversion that may lead to unexpected results. To avoid this issue, always ensure that all operands are of the same data type or cast them appropriately before performing calculations.

Q: Why does my program produce incorrect trigonometric results when using angles greater than π?

A: Trigonometric functions in C have a limited precision, which may lead to inaccurate results when calculating the sine or cosine of angles very close to π. To avoid this issue, you can use iterative methods like Gregory-Newton's method for higher precision calculations.

Q: Why does my program return incorrect trigonometric results when using angles close to 0 or π?

A: Trigonometric functions in C have a limited precision, which may lead to inaccurate results when calculating the sine or cosine of angles very close to 0 or π. To avoid this issue, you can use iterative methods like Gregory-Newton's method for higher precision calculations. Additionally, you can use Taylor series expansions around these points to improve accuracy.

Q: Why does my program return incorrect square root results when the number is negative?

A: The sqrt() function in C calculates the positive square root of a non-negative number. If you provide a negative number, it will return an error or NaN (Not a Number). To handle this case, you can use conditional statements to check if the input is negative and return an appropriate message or calculate the complex square root using other mathematical functions.

Q: Why does my program produce incorrect results when using floating-point arithmetic with large numbers?

A: Floating-point numbers in C have a limited precision, which may lead to inaccurate results when performing calculations with very large or small numbers. To avoid this issue, you can use libraries like GMP (GNU Multiple Precision Arithmetic Library) for high-precision arithmetic operations.

Q: Why does my program return incorrect trigonometric results when using angles close to π/2?

A: Trigonometric functions in C have a limited precision, which may lead to inaccurate results when calculating the sine or cosine of angles very close to π/2. To avoid this issue, you can use iterative methods like Gregory-Newton's method for higher precision calculations. Additionally, you can use Taylor series expansions around these points to improve accuracy.