C Examples Library

48 examples · all runnable online, source viewable, free to download

Application-level C examples — not syntax drills, but complete, ready-to-use utilities and mini systems. Run every example online, inspect the source and download it in one click. Pair it with the C tutorial and C reference for systematic learning.

Category:
Text Normalizer: Trim, Collapse Spaces and Title Case
Text Normalizer: Trim, Collapse Spaces and Title CaseA complete command-line text cleaner: trims leading/trailing whitespace, collapses runs of spaces, converts to title case, and reports word/character counts after cleaning. Three inputs cover a normal sentence, a messy-spacing sentence and an empty-string edge case.🌱 Beginner#fn-strlen#fn-toupper#fn-isdigit
Delimiter Splitter: keep empty fields when splitting and joining
Delimiter Splitter: keep empty fields when splitting and joiningA CSV line parser: splits a record on commas while preserving empty fields created by consecutive delimiters, then re-joins the fields with another delimiter. The hand-written scanner (instead of strtok) handles empty and trailing fields correctly, which matters for real config and table rows.⚡ Intermediate#fn-strlen#fn-strncmp#kw-char
Template Filler: replace {{key}} placeholders, keep unknown keys
Template Filler: replace {{key}} placeholders, keep unknown keysA lightweight template engine: scans {{key}} placeholders and replaces them with values from a lookup table; unknown keys are kept verbatim so missing data stays visible. Two templates show full replacement and the missing-key case, useful for emails, notifications and config snippets.⚡ Intermediate#kw-char#fn-strncmp#fn-strlen
Terminal Table: auto column widths with left/right alignment
Terminal Table: auto column widths with left/right alignmentA terminal table renderer: scans every cell to compute the maximum width per column, then prints an ASCII table with borders; text columns are left-aligned and numeric columns right-aligned. A struct array describes rows and alignment, a practical pattern for reports, listings and CLI output.⚡ Intermediate#fn-printf#fn-strlen#kw-struct
Markdown TOC Generator: skip code fences, extract headings
Markdown TOC Generator: skip code fences, extract headingsA Markdown outline extractor: scans the document line by line, recognises heading levels # through ####, skips fake headings inside ``` code fences, and prints an indented table of contents plus a heading count. Demonstrates state-machine line parsing and indentation math.⚡ Intermediate#fn-strncmp#kw-char#fn-strlen
Run-Length Encoding: compress, decompress and verify the round trip
Run-Length Encoding: compress, decompress and verify the round tripA complete RLE codec: encodes runs of repeated characters as count+character, decodes them back, and verifies round-trip equality on three inputs. Handles two-digit counts such as 12W and text with no repeats — a basic technique for text and binary preprocessing.⚡ Intermediate#kw-char#fn-strlen#fn-printf
Base64 Codec: 3-byte blocks and padding rules
Base64 Codec: 3-byte blocks and padding rulesA from-scratch standard Base64 codec: packs every 3 bytes into 24 bits, splits them into four 6-bit indexes, and pads with = when fewer than 3 bytes remain. The decoder merges the indexes back and restores the exact byte count; three inputs verify the round trip.⚡ Intermediate#fn-strlen#fn-strchr#kw-char
URL Percent-Encoding: unreserved whitelist and %XX decoding
URL Percent-Encoding: unreserved whitelist and %XX decodingImplements the core URL encoding rules: letters, digits and - _ . ~ pass through unchanged, every other byte becomes %XX; the decoder turns %XX back into bytes and verifies the round trip. Three inputs cover a query string, a full URL and an email address.🌱 Beginner#fn-strlen#kw-char#kw-unsigned
Hex Viewer: offset, hex bytes and ASCII in one view
Hex Viewer: offset, hex bytes and ASCII in one viewA standard hexdump utility: 16 bytes per row, offsets on the left, hex bytes grouped by eight in the middle, printable ASCII on the right with dots for the rest. The buffer deliberately includes 0x00, 0x01, 0x7F and 0xFF so the non-printable handling is visible.🌱 Beginner#fn-printf#kw-char#kw-unsigned
Morse Code Codec: letter/digit table and word separators
Morse Code Codec: letter/digit table and word separatorsA complete Morse codec: a 36-entry table maps letters and digits to dots and dashes, words are separated by /; the decoder splits tokens on spaces and restores word breaks at /, then verifies SOS C 2026 round-trips. Shows table lookup, case folding and token parsing.⚡ Intermediate#fn-toupper#fn-strlen#kw-char
JSON String Escaping: quotes, backslashes, newlines and control bytes
JSON String Escaping: quotes, backslashes, newlines and control bytesEscapes and unescapes JSON strings: quotes and backslashes get a leading backslash; newline, carriage return, tab, backspace and form feed use short escapes such as \n; other control bytes become \u00XX. The decoder restores everything and checks the round trip — a foundation for building JSON, logs and API payloads.⚡ Intermediate#fn-strlen#fn-printf#kw-char
FNV-1a Hash: 32-bit string fingerprints and avalanche effect
FNV-1a Hash: 32-bit string fingerprints and avalanche effectImplements the classic 32-bit FNV-1a hash: XOR each byte then multiply by the FNV prime, printing an 8-digit hex fingerprint. Hashes six strings, then compares two inputs differing by one character and counts how many bits changed — a direct look at the avalanche effect.⚡ Intermediate#kw-unsigned#fn-strlen#kw-char
RPN Calculator: stack-based evaluation with error checks
RPN Calculator: stack-based evaluation with error checksEvaluates Reverse Polish notation with a stack: numbers are pushed, operators pop two operands, compute and push the result; a single remaining value is the answer. Demonstrates detection of overflow, underflow, division by zero and leftover operands across five test cases.⚡ Intermediate#kw-double#kw-struct#fn-printf
Ring Buffer: fixed-capacity queue that overwrites the oldest item
Ring Buffer: fixed-capacity queue that overwrites the oldest itemImplements a five-slot ring buffer: head and count describe the logical order; when full, a push overwrites the oldest item and advances head, and a pop takes from head and wraps around. Pushing 1 through 7 shows 1 and 2 being evicted, then pops verify the order.⚡ Intermediate#kw-struct#kw-int#fn-printf
Hash Map: separate chaining and load-factor observation
Hash Map: separate chaining and load-factor observationA string-to-int hash map with seven buckets and separate chaining: the hash accumulates each character in base 31 and takes the modulus; insert, update, lookup, delete and traversal are supported. Prints each bucket chain, the element count and load factor, and shows duplicate-key updates and deletion.🔥 Advanced#kw-struct#fn-malloc#fn-free
Binary Search Tree: insertion, traversals and height
Binary Search Tree: insertion, traversals and heightImplements recursive insertion into a binary search tree, then prints inorder and preorder traversals plus height, node count and lookups. The inorder sequence must be strictly increasing, which verifies the BST property; nine keys produce height four, with both hit and miss lookups shown.🔥 Advanced#kw-struct#fn-malloc#fn-free
Singly Linked List: push front/back, delete, reverse and free
Singly Linked List: push front/back, delete, reverse and freeA complete singly linked list exercise: push_front and push_back build 1→2→3→4, a value is deleted, three pointers reverse the list in place, and all nodes are freed. Functions take Node **head so the caller's pointer stays correct after head deletion or reversal.⚡ Intermediate#kw-struct#fn-malloc#fn-free
Min-Heap: sift-up insert, sift-down extract and priority order
Min-Heap: sift-up insert, sift-down extract and priority orderAn array-based min-heap: insertion sifts the new element up, extraction moves the last element to the root and sifts it down, keeping every parent no larger than its children. Inserts eight numbers, prints the heap after each step, then extracts them in order 1, 3, 7, 8, 19, 25, 31, 42.🔥 Advanced#kw-int#kw-struct#fn-printf
GCD and LCM: Euclid's algorithm, iterative and recursive
GCD and LCM: Euclid's algorithm, iterative and recursiveProvides both iterative and recursive Euclid's algorithm for GCD, then computes LCM as a/gcd*b with long long and boundary checks to avoid multiplication overflow. Tests 48/18, 17/5, 0/9, a negative pair and 1071/462.🌱 Beginner#kw-int#kw-long#fn-printf
Quadratic Solver: discriminant, double root and degenerate cases
Quadratic Solver: discriminant, double root and degenerate casesSolves ax²+bx+c=0 by discriminant: two real roots when D>0, a double root when D=0, no real roots when D<0; also handles a=0 linear and a=b=0 degenerate cases. Square root uses a self-contained Newton iteration, avoiding libm so the single file compiles directly.🌱 Beginner#kw-double#kw-int#fn-printf
Big Factorial: decimal digit array with carry propagation
Big Factorial: decimal digit array with carry propagationStores a big integer as an array of decimal digits, multiplies from 2 through 50 digit by digit with carry propagation, and produces exact 50! (65 digits). Also prints digit counts for 10! through 50! to show factorial growth — an introduction to hand-written big-number arithmetic.⚡ Intermediate#kw-int#kw-const#fn-printf
Levenshtein Distance: DP matrix and edit costs
Levenshtein Distance: DP matrix and edit costsComputes edit distance with a 2D DP: dp[i][j] takes the minimum of delete, insert and substitute, with zero substitution cost for equal characters. Prints the full 8×8 matrix and distance 3 for kitten→sitting, then tests flaw→lawn and identical strings.🔥 Advanced#kw-int#kw-char#fn-strlen
Union-Find: path compression, union by rank and components
Union-Find: path compression, union by rank and componentsImplements a 10-element union-find: find compresses paths recursively, unite merges by rank and maintains a component count. Runs seven unions (including a self-union and an already-connected pair), queries four connectivity pairs, then prints the parent array and remaining components.🔥 Advanced#kw-struct#kw-int#fn-printf
Josephus Problem: counting eliminations, array shifts and survivor
Josephus Problem: counting eliminations, array shifts and survivorSimulates n people in a circle with an array: each round eliminates the k-th person, shifts later elements forward, and wraps the index modulo the remaining count; repeats until one remains. Solves (10,3), (41,3) and (7,2), printing elimination order and survivor.⚡ Intermediate#kw-int#fn-printf#kw-static
Log Writer: timestamps, level tags and read-back counting
Log Writer: timestamps, level tags and read-back countingCreates a temporary log with tmpfile, appends five entries formatted as time [level] message, then rewinds and reads them back: prints each line and counts INFO, WARN and ERROR with strstr. Shows the standard flow of append writing, buffered reading and simple log analysis.🌱 Beginner#fn-fprintf#fn-fgets#fn-fclose
INI Config Parser: sections, key/value pairs and trimming
INI Config Parser: sections, key/value pairs and trimmingWrites an INI config to a temp file and parses it line by line: recognises [section] headers, splits each pair at the first =, trims surrounding whitespace, and prints entries grouped by section. Covers the usual edge cases: blank lines and comment lines are skipped.⚡ Intermediate#fn-fgets#fn-strchr#fn-strlen
CSV Reader: skip header, parse rows, aggregate totals
CSV Reader: skip header, parse rows, aggregate totalsGenerates a four-row product CSV, skips the header, then uses sscanf with %[^,] for the name, %d for quantity and %lf for unit price; prints each row and accumulates total quantity and value. Shows the most common field-splitting and type-conversion combination in CSV parsing.🌱 Beginner#fn-fgets#fn-printf#kw-char
Binary Records: fwrite/fread round trip for a struct array
Binary Records: fwrite/fread round trip for a struct arrayWrites three struct records (id, name, score) to a temp file with fwrite, reads them back with fread and prints each one, then compares id, name and score to confirm an exact binary round trip. Demonstrates the basic read/write pattern for fixed-length record files.🔥 Advanced#fn-fwrite#fn-fread#kw-struct
Merge Sorted Files: combine two ascending sequences into one output
Merge Sorted Files: combine two ascending sequences into one outputWrites two ascending integer sequences to separate temp files, reads them into arrays, merges them with two pointers into one sorted result, writes that to a third file and reads it back for printing. Shows the core merge loop plus the full path from files as input to files as output.⚡ Intermediate#fn-printf#kw-int#kw-char
Inverted Index: word-to-line mapping with de-duplication
Inverted Index: word-to-line mapping with de-duplicationBuilds an inverted index from a three-line document: tokenises each line, lowercases the words, and maps every word to the line numbers where it appears; repeated occurrences on the same line are recorded once. Prints nine terms in first-seen order with their line lists — a miniature search index.🔥 Advanced#fn-strlen#fn-tolower#kw-char
Month Calendar: first weekday and leap-year month lengths
Month Calendar: first weekday and leap-year month lengthsGiven a year and month, Zeller's congruence finds the weekday of the 1st, then the grid is laid out Monday through Sunday; February automatically uses 28 or 29 days based on the leap-year rule. Prints November 2026, February 2024 and January 2026.⚡ Intermediate#fn-printf#kw-int#kw-static
Weekday Finder: Zeller's congruence across six dates
Weekday Finder: Zeller's congruence across six datesImplements Zeller's congruence for any Gregorian date: January and February are folded into months 13 and 14 of the previous year, then the last two year digits and the century are plugged into the formula. Prints weekday names for six dates including 2026-11-28, 2000-01-01 and 2024-02-29.🌱 Beginner#fn-printf#kw-int#kw-static
Date Difference: civil-to-serial days across leap years
Date Difference: civil-to-serial days across leap yearsUses Howard Hinnant's days_from_civil algorithm to convert a date into serial days since 1970, subtracts them for an exact day count, and also reports whole weeks plus remainder days. Tests a year boundary, a leap day (2024-02-28 to 03-01) and the same date.⚡ Intermediate#kw-long#kw-int#fn-printf
Duration Formatter: parse HH:MM:SS and print d/h/m/s
Duration Formatter: parse HH:MM:SS and print d/h/m/sParses five duration strings from 00:00:00 to 36:00:00 into total seconds, then formats them back as days hours:minutes:seconds, adding a day prefix when needed. Also formats 45, 3600 and 90061 seconds directly to verify boundaries and day rollover.🌱 Beginner#fn-printf#kw-long#kw-int
Unix Timestamp: seconds to UTC date and time
Unix Timestamp: seconds to UTC date and timeImplements the inverse civil_from_days algorithm to turn serial days since 1970 back into a date, then splits the seconds within a day into hours, minutes and seconds. Converts timestamps 0, 1000000000, 1764000000, 2147483647 and 1700000000 into UTC, covering the epoch and the 2038 boundary.🔥 Advanced#kw-long#fn-printf#kw-int
Age Calculator: birthday-not-yet logic and leap-day validation
Age Calculator: birthday-not-yet logic and leap-day validationComputes full years as the year difference minus one when this year's birthday has not arrived, and validates the birth date (month range, days per month, February 29 in leap years). With today fixed at 2026-11-28, tests birthday passed, not yet, born today, a future date and February 29.🌱 Beginner#kw-struct#fn-printf#kw-int
Reference Counting: shared buffer with retain/release
Reference Counting: shared buffer with retain/releaseImplements a ref-counted shared buffer: a struct header stores refs, a flexible array holds the text; retain increments and release decrements, freeing at zero. Demonstrates the full lifecycle of create, retain, two releases, and confirms both pointers address the same block.🔥 Advanced#kw-struct#fn-malloc#fn-free
Leak Checker: live block and byte accounting
Leak Checker: live block and byte accountingWraps malloc/free with a Header before each block recording its size, tracks live block and byte counts, and prints the running totals on every alloc/free. Allocates three blocks, frees two, intentionally leaks one, and reports final live blocks and bytes — a minimal leak detector.⚡ Intermediate#fn-malloc#fn-free#kw-sizeof
Command Table: function-pointer dispatch for text commands
Command Table: function-pointer dispatch for text commandsBuilds a command table of name plus function pointer, registers echo, upper, count and help, splits each input line at the first space into command and argument, looks up the table and calls the matching function; misses print unknown. Shows table-driven dispatch replacing a long if/else chain.⚡ Intermediate#fn-strcmp#kw-static#kw-void
Generic Container: void* payloads with print callbacks
Generic Container: void* payloads with print callbacksDesigns a Box struct with a const void* data field and a print function pointer. Stores int, double and string values in one array, each item carrying its own printer, and iterates calling the callback to print correctly. Demonstrates the classic void* type erasure plus callback type recovery.🔥 Advanced#kw-void#kw-struct#kw-static
Fixed Block Pool: bitmap marking, allocation and reuse
Fixed Block Pool: bitmap marking, allocation and reuseImplements a fixed pool of eight 32-byte blocks: a used array acts as an occupancy bitmap, alloc scans for the first free slot and returns its index, free clears the mark, and allocating after freeing a middle block reuses that slot. Prints a #/. bitmap after each step to show fragmentation and reuse.🔥 Advanced#kw-struct#kw-static#fn-printf
String Interning: de-duplication, refcounts and pointer equality
String Interning: de-duplication, refcounts and pointer equalityMaintains an intern table of up to 16 entries: identical content reuses the existing pointer and increments refs, otherwise a malloc'd copy is registered. After interning hello, world, hello, C and world, pointer comparison proves identical strings share one address; all entries are released at the end.🔥 Advanced#fn-malloc#fn-free#fn-strcmp
Inventory Manager: stock moves, shortages and low-stock alerts
Inventory Manager: stock moves, shortages and low-stock alertsMaintains product stock in a struct array with lookup by id, sale deduction, restock and unknown-item handling; sales check available quantity, then the program prints the stock table, total inventory value and items below five units. A minimal inventory model.⚡ Intermediate#kw-struct#fn-printf#kw-int
Bank Accounts: deposit, withdraw, transfer and balance checks
Bank Accounts: deposit, withdraw, transfer and balance checksImplements deposit, withdraw and account-to-account transfer with account structs; every operation first checks a positive amount and sufficient balance, printing a rejection instead of changing the balance. Prints final balances for three accounts, demonstrating validate-then-mutate.⚡ Intermediate#kw-struct#fn-printf#kw-double
Todo List: add, complete, delete and priority display
Todo List: add, complete, delete and priority displayA fixed-capacity todo list: each task has an auto-increment id, title, priority and done flag; supports add, complete by id, delete by id with later elements shifted forward, listing and open-task counting. Demonstrates basic CRUD on a struct array.🌱 Beginner#kw-struct#fn-printf#fn-strlen
Payroll: hours × rate, progressive tax and net pay table
Payroll: hours × rate, progressive tax and net pay tableComputes gross pay from hours and hourly rate, then applies a two-bracket progressive tax: 10% up to 1000 and 20% above it; prints each employee's gross, tax and net plus company totals. The table is aligned with printf widths — a simplified payroll model.⚡ Intermediate#kw-struct#fn-printf#kw-double
Seat Booking: 2D map, reserve, cancel and occupancy count
Seat Booking: 2D map, reserve, cancel and occupancy countRepresents seats as a 7×6 character matrix, '.' free and 'X' booked; reserve validates row/column bounds and occupancy, cancel only releases booked seats, and the program prints the map and counts free seats. Shows a 2D array as a state table with full bounds checking.🌱 Beginner#kw-char#kw-static#fn-printf
Vote Counter: tally, percentages and winner detection
Vote Counter: tally, percentages and winner detectionStores candidate names and vote counts in a struct array, walks 12 ballots (including one abstention) to accumulate valid votes; then computes each candidate's percentage, finds the highest count and prints the winner. Demonstrates index mapping, counting and a simple maximum search.🌱 Beginner#kw-struct#fn-printf#kw-int
No examples at this difficulty in this category

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏