All Courses
C Basics

C Standard Libraries & Math Utilities

C provides a minimal core language. Most day-to-day utilities—such as mathematical operations, character checks, and random number generation—are provided by the C Standard Library.

1. Mathematical Operations (<math.h>)

The <math.h> header contains declarations for floating-point calculations.

[!NOTE] When compiling C programs that use <math.h> on Linux or GCC, you must link the math library manually by appending the -lm flag: gcc program.c -o program -lm.

Common math functions: - sqrt(x): Returns the square root of $x$ (double). - pow(base, exp): Returns $base^{exp}$ (double). - abs(x) (in <stdlib.h>): Returns the absolute value of an integer $x$. - fabs(x): Returns the absolute value of a floating-point number $x$. - ceil(x) / floor(x): Rounds a float up or down to the nearest integer.

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

int main() {
    double base = 2.0, exponent = 3.0;
    double power = pow(base, exponent); // 2^3 = 8
    double root = sqrt(16.0);           // sqrt(16) = 4

    printf("2^3 = %.1lf\n", power);
    printf("Square root of 16 = %.1lf\n", root);
    return 0;
}

2. Character Classification & Conversion (<ctype.h>)

Used to analyze and modify individual characters. They return non-zero (true) or zero (false): - isalpha(c): Checks if character is alphabetic. - isdigit(c): Checks if character is a decimal digit (0-9). - isalnum(c): Checks if character is alphanumeric. - isspace(c): Checks if character is a space, tab, or newline. - toupper(c) / tolower(c): Converts characters between upper and lower case.

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

int main() {
    char ch = 'a';
    if (isalpha(ch)) {
        printf("'%c' is a letter. Capitalized: '%c'\n", ch, toupper(ch));
    }
    return 0;
}

3. Random Numbers and Time (<stdlib.h> & <time.h>)

C generates pseudo-random numbers using rand(). If you don't seed the generator, rand() will produce the exact same sequence of numbers every time the program runs. To get unique numbers, seed the generator with the current system time using srand(time(NULL)):

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    // Seed generator with current calendar time
    srand((unsigned int)time(NULL));

    // Generate 5 random numbers between 1 and 100
    for (int i = 0; i < 5; i++) {
        int random_num = (rand() % 100) + 1; // scale with modulus
        printf("Random %d: %d\n", i + 1, random_num);
    }
    return 0;
}