LearnFrenzy
Sign in Take a free test

C Programming · Topic 23 of 23

C Library Functions

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

C Library Functions · Study material

C library functions are the ready-made functions of the C standard library – printf(), sqrt(), strlen(), qsort(), malloc() and about two hundred more. Their declarations live in header files such as <stdio.h> and <math.h>; the compiled code is in the library that the linker adds to your program. Knowing which header holds which function, what each function returns and where the traps are is essential for exams, interviews and everyday C. This page tours the most used headers with programs you can run, followed by 40 practice questions checked on a real compiler.

On this page

  • What library functions and header files are, and why to use them
  • math.h, string.h, stdlib.h, ctype.h and time.h with examples
  • Sorting and searching with qsort() and bsearch()
  • A table of all standard headers

Library functions and header files

A header contains declarations (prototypes, types, macros), not the function bodies. #include <math.h> tells the compiler the type of sqrt(); the linker then takes its code from the C library. Calling a function without its header is an error in modern C, because functions must be declared before they are called. (On some Linux systems the math functions also need -lm when linking.)

Note that main() is not a library function: you write it, and the startup code calls it.

Why use the standard library?

  • Correct – used and tested by millions of programs.
  • Fast – tuned for each platform, often in assembly.
  • Saves time – no need to rewrite sorting, formatting or maths.
  • Portable – the same call works on every conforming compiler.

Mathematics: <math.h>

Math functions take and return double (with f and l versions such as sqrtf for float and long double). Angles are in radians.

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

int main(void) {
    double x = 12;
    printf("sqrt(%.0f) = %.2f\n", x, sqrt(x));                 /* the classic example */
    printf("pow(2, 10) = %.0f, cbrt(27) = %.0f\n", pow(2, 10), cbrt(27));
    printf("fabs(-7.5) = %.1f, hypot(3, 4) = %.1f\n", fabs(-7.5), hypot(3, 4));
    printf("ceil(2.1) = %.0f, floor(2.9) = %.0f, round(2.5) = %.0f\n", ceil(2.1), floor(2.9), round(2.5));
    printf("sin(pi/2) = %.1f, log10(1000) = %.0f, exp(1) = %.4f\n", sin(acos(-1) / 2), log10(1000), exp(1));
    return 0;
}

Output

sqrt(12) = 3.46
pow(2, 10) = 1024, cbrt(27) = 3
fabs(-7.5) = 7.5, hypot(3, 4) = 5.0
ceil(2.1) = 3, floor(2.9) = 2, round(2.5) = 3
sin(pi/2) = 1.0, log10(1000) = 3, exp(1) = 2.7183

Strings and memory: <string.h>

str… functions work on '\0'-terminated strings; mem… functions work on any bytes and take an explicit length. strcmp() returns a negative, zero or positive value – not necessarily −1 or 1. memmove() is the only copy function that handles overlapping regions.

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[32] = "Learn";
    strcat(name, "Frenzy");                               /* append */
    printf("%s has %zu characters\n", name, strlen(name));
    printf("strcmp: %d %d\n", strcmp("apple", "apricot") < 0, strcmp("C", "C") == 0);
    printf("first 'e' at %td, \"Fren\" at %td\n", strchr(name, 'e') - name, strstr(name, "Fren") - name);

    char copy[32];
    memcpy(copy, name, strlen(name) + 1);                 /* +1 copies the '\0' too */
    memset(copy, '*', 5);
    printf("%s\n", copy);
    return 0;
}

Output

LearnFrenzy has 11 characters
strcmp: 1 1
first 'e' at 1, "Fren" at 5
*****Frenzy

Utilities: <stdlib.h>

<stdlib.h> holds memory allocation (malloc, free), conversions (strtol, strtod, atoi), integer helpers (abs, div), pseudo-random numbers (rand, srand), sorting and searching (qsort, bsearch) and program control (exit, atexit, getenv).

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

int main(void) {
    div_t d = div(17, 5);                                /* quotient and remainder together */
    printf("17 = 5 * %d + %d\n", d.quot, d.rem);
    printf("abs(-9) = %d, labs(-90000L) = %ld\n", abs(-9), labs(-90000L));
    printf("strtol(\"ff\", 16) = %ld, strtod(\"2.5e3\") = %.1f\n", strtol("ff", NULL, 16), strtod("2.5e3", NULL));
    printf("RAND_MAX is at least 32767: %d\n", RAND_MAX >= 32767);
    return 0;
}

Output

17 = 5 * 3 + 2
abs(-9) = 9, labs(-90000L) = 90000
strtol("ff", 16) = 255, strtod("2.5e3") = 2500.0
RAND_MAX is at least 32767: 1
#include <stdio.h>
#include <stdlib.h>

static int by_value(const void *a, const void *b) {
    int x = *(const int *) a, y = *(const int *) b;
    return (x > y) - (x < y);                 /* no overflow, unlike x - y */
}

int main(void) {
    int a[] = {42, 7, 19, 88, 3, 56};
    size_t n = sizeof a / sizeof a[0];
    qsort(a, n, sizeof a[0], by_value);
    for (size_t i = 0; i < n; i++)
        printf("%d ", a[i]);

    int key = 56;
    int *hit = bsearch(&key, a, n, sizeof a[0], by_value);
    printf("\n56 found at index %td\n", hit - a);
    return 0;
}

Output

3 7 19 42 56 88
56 found at index 4

Characters: <ctype.h>

Classification (isalpha, isdigit, isspace, isupper, ispunct…) returns non-zero for true – not necessarily 1. toupper/tolower convert one character. Pass values as unsigned char (or EOF): a negative char value is undefined behaviour.

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

int main(void) {
    const char *s = "Room 42B, Floor 3!";
    int letters = 0, digits = 0, spaces = 0, punct = 0;
    for (const char *p = s; *p; p++) {
        unsigned char c = (unsigned char) *p;     /* ctype functions need unsigned char values */
        if (isalpha(c)) letters++;
        else if (isdigit(c)) digits++;
        else if (isspace(c)) spaces++;
        else if (ispunct(c)) punct++;
        putchar(toupper(c));
    }
    printf("\nletters %d, digits %d, spaces %d, punctuation %d\n", letters, digits, spaces, punct);
    return 0;
}

Output

ROOM 42B, FLOOR 3!
letters 10, digits 3, spaces 3, punctuation 2

Date and time: <time.h>

time() returns the current calendar time as time_t (seconds since 1970 on most systems). gmtime()/localtime() break it into a struct tm, mktime() converts back, strftime() formats it and difftime() subtracts two times. clock() measures processor time.

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

int main(void) {
    time_t t = 1800000000;                     /* seconds since 1 Jan 1970, UTC */
    struct tm *utc = gmtime(&t);
    char text[64];
    strftime(text, sizeof text, "%Y-%m-%d %H:%M:%S, %A", utc);
    printf("%s\n", text);
    printf("day of year %d, %.0f days after the epoch\n", utc->tm_yday + 1, difftime(t, 0) / 86400);
    return 0;
}

Output

2027-01-15 08:00:00, Friday
day of year 15, 20833 days after the epoch

The standard headers

HeaderContentsHeaderContents
stdio.hinput/output, filesstdlib.hmemory, conversion, sorting, exit
string.hstrings and memory blocksmath.hmathematics
ctype.hcharacter tests and casetime.hdate and time
assert.hassertionserrno.herror numbers
limits.h / float.htype limitsstdint.h / inttypes.hfixed-width integers
stdbool.hbool, true, falsestddef.hsize_t, NULL, offsetof
stdarg.hvariable argumentssetjmp.hnon-local jumps
signal.hsignal handlinglocale.hlocalisation
threads.h / stdatomic.hthreads, atomics (C11)stdckdint.h / stdbit.hchecked arithmetic, bit utilities (C23)

Key points to remember

  • Include the right header for every library function you call.
  • strlen does not count '\0'; buffers need strlen + 1 bytes.
  • Use memmove, not memcpy, when regions overlap.
  • Compare strings with strcmp, never with ==.
  • Cast to unsigned char before calling ctype functions.

Frequently asked questions

Is printf a keyword?

No. printf is an ordinary library function declared in <stdio.h>; you could even name a local variable printf (please don't).

Why does my program say "undefined reference to sqrt"?

On Linux with GCC the maths library is separate: link with -lm.

Is rand() good enough for random numbers?

For games and simulations, yes; for passwords or keys, no – use the operating system's secure random source.

Where can I learn more?

Read String Functions in C and Searching and Sorting in C, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links