Chapter 21 of 44

Math & Character Library Functions in C

Suppose you need the square root of a number, or you want to check whether a character typed by the user is a digit. You could write your own code for these, but you don't have to.

C already comes with ready-made library functions for common tasks. In this topic we'll look at two very useful groups of them:

  • Math functions from <math.h>, such as sqrt(), pow() and ceil()

  • Character functions from <ctype.h>, such as isdigit() and toupper()

What is a Library Function?

A library function is a pre-written, tested function provided by the C standard library. To use one, we include the header file that declares it and then call it like any other function.

#include <math.h>     // for sqrt(), pow(), ...
#include <ctype.h>    // for isdigit(), toupper(), ...

We already used library functions such as printf() from <stdio.h> and strlen() from <string.h>. The idea is exactly the same.


Math Functions (<math.h>)

Most math functions take double arguments and return a double. So we usually print their results with %f (or %.2f for two decimal places).

Function

Meaning

Example

Result

sqrt(x)

Square root

sqrt(25.0)

5.0

pow(x, y)

x raised to the power y

pow(2.0, 10.0)

1024.0

cbrt(x)

Cube root

cbrt(27.0)

3.0

fabs(x)

Absolute value of a floating-point number

fabs(-7.5)

7.5

hypot(x, y)

Square root of x² + y²

hypot(3.0, 4.0)

5.0

fmod(x, y)

Floating-point remainder of x / y

fmod(10.0, 3.0)

1.0

exp(x)

e raised to the power x

exp(1.0)

2.71828...

log(x)

Natural logarithm (base e)

log(10.0)

2.30258...

log10(x)

Logarithm base 10

log10(1000.0)

3.0

log2(x)

Logarithm base 2

log2(64.0)

6.0

sin(x), cos(x), tan(x)

Trigonometric functions (x in radians)

cos(0.0)

1.0

Note: log in C means the natural log (ln), not log base 10. This confuses many students.

Example: Common Math Functions

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

int main()
{
    printf("sqrt(25)    = %.2f\n", sqrt(25.0));
    printf("pow(2, 10)  = %.2f\n", pow(2.0, 10.0));
    printf("cbrt(27)    = %.2f\n", cbrt(27.0));
    printf("fabs(-7.5)  = %.2f\n", fabs(-7.5));
    printf("hypot(3, 4) = %.2f\n", hypot(3.0, 4.0));
    printf("fmod(10, 3) = %.2f\n", fmod(10.0, 3.0));
    printf("exp(1)      = %.4f\n", exp(1.0));
    printf("log(10)     = %.4f\n", log(10.0));
    printf("log10(1000) = %.2f\n", log10(1000.0));
    printf("log2(64)    = %.2f\n", log2(64.0));

    return 0;
}

Output:

sqrt(25)    = 5.00
pow(2, 10)  = 1024.00
cbrt(27)    = 3.00
fabs(-7.5)  = 7.50
hypot(3, 4) = 5.00
fmod(10, 3) = 1.00
exp(1)      = 2.7183
log(10)     = 2.3026
log10(1000) = 3.00
log2(64)    = 6.00

Linking the Math Library on Linux

On Linux with GCC, the math functions live in a separate library called libm. If you see an error like undefined reference to `sqrt', add -lm at the end of the compile command:

gcc program.c -o program -lm

Including <math.h> only gives the compiler the declarations. -lm tells the linker where the actual code of these functions is. (On Windows and macOS this flag is usually not needed. We'll see the difference between declarations and linking in the Compilation Process topic.)


Rounding Functions: ceil, floor, round, trunc

These four functions are a favourite in exams and interviews, especially with negative numbers.

Function

Rule

Easy way to remember

ceil(x)

Smallest whole number greater than or equal to x

Go up (towards +∞)

floor(x)

Largest whole number less than or equal to x

Go down (towards −∞)

round(x)

Nearest whole number; halfway cases go away from zero

Normal school rounding

trunc(x)

Simply removes the decimal part

Go towards zero

For example, for -2.7: going up gives -2, so ceil(-2.7) is -2; going down gives -3, so floor(-2.7) is -3; dropping the decimal part gives -2, so trunc(-2.7) is -2.

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

int main()
{
    double values[] = {2.4, 2.5, 2.7, -2.4, -2.5, -2.7};

    printf("value   ceil   floor  round  trunc\n");

    for (int i = 0; i < 6; i++)
    {
        double v = values[i];
        printf("%5.1f  %5.1f  %5.1f  %5.1f  %5.1f\n",
               v, ceil(v), floor(v), round(v), trunc(v));
    }

    return 0;
}

Output:

value   ceil   floor  round  trunc
  2.4    3.0    2.0    2.0    2.0
  2.5    3.0    2.0    3.0    2.0
  2.7    3.0    2.0    3.0    2.0
 -2.4   -2.0   -3.0   -2.0   -2.0
 -2.5   -2.0   -3.0   -3.0   -2.0
 -2.7   -2.0   -3.0   -3.0   -2.0

Look carefully at the negative rows: floor(-2.4) is -3, not -2, because -3 is the next whole number below -2.4. Also note that all four functions return a double, not an int.


Worked Examples

1. Compound Interest

Formula: A = P × (1 + R/100)n

For P = 10000, R = 8% per year, n = 3 years:

A = 10000 × (1.08)³
  = 10000 × 1.259712
  = 12597.12
Interest = A − P = 2597.12
#include <stdio.h>
#include <math.h>

int main()
{
    double principal = 10000.0;
    double rate = 8.0;      // percent per year
    int years = 3;

    double amount = principal * pow(1 + rate / 100, years);

    printf("Amount   = %.2f\n", amount);
    printf("Interest = %.2f\n", amount - principal);

    return 0;
}

Output:

Amount   = 12597.12
Interest = 2597.12

Here years is an int, but it is automatically converted to double when passed to pow(), because <math.h> declares that pow() takes double parameters.

2. Roots of a Quadratic Equation

For ax² + bx + c = 0, the roots are (−b ± √(b² − 4ac)) / 2a. For x² − 5x + 6 = 0: the discriminant is 25 − 24 = 1, so the roots are (5 ± 1) / 2 = 3 and 2.

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

int main()
{
    double a = 1, b = -5, c = 6;   // x^2 - 5x + 6 = 0

    double d = b * b - 4 * a * c;

    if (d >= 0)
    {
        double root1 = (-b + sqrt(d)) / (2 * a);
        double root2 = (-b - sqrt(d)) / (2 * a);
        printf("Roots: %.2f and %.2f\n", root1, root2);
    }
    else
    {
        printf("No real roots\n");
    }

    return 0;
}

Output:

Roots: 3.00 and 2.00

We check d >= 0 first because the square root of a negative number is not a real number.

3. Degrees vs Radians

The trigonometric functions expect the angle in radians. To convert: radians = degrees × π / 180.

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

int main()
{
    double pi = acos(-1.0);
    double angleDeg = 30.0;
    double angleRad = angleDeg * pi / 180.0;

    printf("sin(30 degrees) = %.4f\n", sin(angleRad));
    printf("cos(60 degrees) = %.4f\n", cos(60.0 * pi / 180.0));
    printf("sin(30) radians = %.4f\n", sin(30.0));

    return 0;
}

Output:

sin(30 degrees) = 0.5000
cos(60 degrees) = 0.5000
sin(30) radians = -0.9880

Writing sin(30.0) gives the sine of 30 radians, which is a completely different answer. Also, the constant M_PI that you may see online is not part of standard C (it comes from POSIX), so it may not exist on every compiler. acos(-1.0) is a portable way to get π.


Absolute Value and Remainder

There are separate functions for integers and floating-point numbers:

Function

Header

Works on

Example

abs(x)

<stdlib.h>

int

abs(-7) → 7

fabs(x)

<math.h>

double

fabs(-7.9) → 7.9

% operator

built in

integers

-7 % 3 → -1

fmod(x, y)

<math.h>

double

fmod(-7.0, 3.0) → -1.0

Two things to remember:

  • abs() is in <stdlib.h>, not <math.h>. Passing it -7.9 converts the value to the int -7 first, so you get 7, not 7.9. Use fabs() for decimals.

  • For both % and fmod(), the result takes the sign of the first number (the dividend). So -7 % 3 is -1, not 2.

Invalid Inputs

Some inputs have no valid real answer:

  • sqrt(-4.0) returns NaN ("Not a Number"). It may print as nan, -nan or similar, depending on the system.

  • log(0.0) returns negative infinity, printed as -inf.

So always check your inputs (like we checked d >= 0 above) instead of relying on these special values.


Character Functions (<ctype.h>)

The <ctype.h> header has functions to test what kind of character we have and to convert between uppercase and lowercase.

Testing Functions

Function

Returns true (non-zero) if the character is...

True for

isalpha(c)

a letter

'a'–'z', 'A'–'Z'

isdigit(c)

a decimal digit

'0'–'9'

isalnum(c)

a letter or a digit

'a', 'Z', '5'

isupper(c)

an uppercase letter

'A'–'Z'

islower(c)

a lowercase letter

'a'–'z'

isspace(c)

a whitespace character

' ', '\n', '\t', '\r', '\v', '\f'

ispunct(c)

a punctuation character

'!', ',', '@'

isxdigit(c)

a hexadecimal digit

'0'–'9', 'a'–'f', 'A'–'F'

(The "True for" column shows the normal "C" locale, which is the default.)

An important detail: these functions return 0 for false and some non-zero value for true. The true value is not always 1. For example, isdigit('7') returns 2048 with the GNU C library on Linux. So always write:

if (isdigit(ch))        // correct
if (isdigit(ch) == 1)   // wrong: may be false even for a digit

Conversion Functions

Function

What it does

Example

toupper(c)

Returns the uppercase version of a lowercase letter; any other character is returned unchanged

toupper('a') → 'A', toupper('5') → '5'

tolower(c)

Returns the lowercase version of an uppercase letter; any other character is returned unchanged

tolower('Q') → 'q'

These functions return the new character. They do not change the variable you pass in, so you must store the result: ch = toupper(ch);

Example: Analysing a String

This program counts letters, digits, spaces and other characters, and then converts the string to uppercase.

#include <stdio.h>
#include <ctype.h>

int main()
{
    char text[] = "Hello World 2026!";
    int letters = 0, digits = 0, spaces = 0, others = 0;

    for (int i = 0; text[i] != '\0'; i++)
    {
        unsigned char ch = (unsigned char)text[i];

        if (isalpha(ch))
            letters++;
        else if (isdigit(ch))
            digits++;
        else if (isspace(ch))
            spaces++;
        else
            others++;
    }

    printf("Letters: %d\n", letters);
    printf("Digits : %d\n", digits);
    printf("Spaces : %d\n", spaces);
    printf("Others : %d\n", others);

    for (int i = 0; text[i] != '\0'; i++)
    {
        text[i] = (char)toupper((unsigned char)text[i]);
    }

    printf("Upper  : %s\n", text);

    return 0;
}

Output:

Letters: 10
Digits : 4
Spaces : 2
Others : 1
Upper  : HELLO WORLD 2026!

Why the (unsigned char) cast? The <ctype.h> functions are only defined for values that fit in an unsigned char (0 to 255 on most systems) or the special value EOF. On many systems char is signed, so characters outside basic ASCII (for example, accented letters) can be stored as negative numbers. Passing such a negative value is undefined behavior. Casting to unsigned char first avoids this problem.

Converting a Digit Character to a Number

Characters are stored as numbers, and the C standard guarantees that '0' to '9' have consecutive codes. So:

int value = '7' - '0';   // value = 7

This trick is used all the time, for example when converting a string like "472" into the number 472, digit by digit.

toupper() vs Manual Conversion

You may see code like ch = ch - 32; to convert to uppercase. This works only for lowercase ASCII letters, and it breaks if ch is already uppercase or is not a letter. toupper() handles every case correctly and is clearer, so prefer it.


Common Mistakes

  • Printing a double result with %d. printf("%d", sqrt(16.0)); is wrong because sqrt() returns a double. Use %f, or cast: (int)sqrt(16.0).

  • Forgetting #include <math.h>. Without the declaration, the compiler doesn't know the function returns a double. Modern compilers report an error or warning.

  • Forgetting -lm on Linux, which causes "undefined reference" errors.

  • Using pow() for exact integer powers. pow() works with floating-point numbers, so very large results may not be exact. For integer powers (like 2n), a simple loop with integer multiplication is safer.

  • Using degrees with sin(), cos(), tan(). Convert to radians first.

  • Comparing isdigit(ch) == 1. Just test for non-zero.

  • Expecting toupper(ch); to change ch. Store the returned value.


Interview Questions

What is the difference between ceil() and floor() for -3.2?

ceil(-3.2) is -3.0 (rounds up towards +∞) and floor(-3.2) is -4.0 (rounds down towards −∞).

What is the difference between abs() and fabs()?

abs() is declared in <stdlib.h> and works on int. fabs() is declared in <math.h> and works on double.

Why do we need -lm when compiling with GCC on Linux?

The header only declares the math functions. Their compiled code is in the separate math library libm, and -lm tells the linker to use it.

What does isdigit() return?

An int: 0 if the character is not a digit, and some non-zero value (not necessarily 1) if it is.

What does log() compute in C?

The natural logarithm (base e). Use log10() for base 10 and log2() for base 2.

What is the output of printf("%.1f", round(-2.5));?

-3.0. round() rounds halfway cases away from zero.

In Simple Words

<math.h> gives us ready-made mathematical functions, and <ctype.h> gives us functions to test and convert characters.

sqrt, pow, cbrt, fabs     → basic math (return double)
ceil, floor, round, trunc → rounding (watch negative numbers!)
sin, cos, tan             → angles in radians
isalpha, isdigit, isspace → test a character (0 = false, non-zero = true)
toupper, tolower          → convert a character (returns the result)

Using library functions saves time and avoids bugs, because they are already written and well tested. Next, we'll move to one of the most important topics in C: pointers.