Lots of the C mini tasks college students discover on-line nonetheless start with #embrace <graphics.h> or #embrace <conio.h>. Each headers come from Borland’s Turbo C of the early Nineteen Nineties. No present compiler ships graphics.h, and conio.h exists solely on Home windows. So the very first thing a newbie learns from these tasks is the way to combat a compiler error that has nothing to do with C.
The 15 tasks on this web page use solely the C customary library, so each builds with a single command on GCC, Clang or Visible Studio. They run from a menu-driven unit converter to a working textual content editor, and they’re grouped in three ranges so you may work by them so as. Every undertaking explains what you’ll construct, the ideas it practices, the way it works and the one or two “why” questions it solutions; the entire, examined program is on GitHub. Each program compiles with zero warnings below GCC, Clang and Visible Studio in C11 and C17, and its pattern classes are re-run routinely on Linux and Home windows each time the code adjustments.
What Is a Mini Challenge in C?
A mini undertaking in C is a small, full program, often a couple of hundred traces in a single file, that solves one actual activity from begin to end: it reads enter, processes it and produces helpful output. Mini tasks flip separate subjects reminiscent of loops, arrays, structs and information into working software program, which is why they’re the same old subsequent step after the fundamentals.
A very good mini undertaking is sufficiently small to complete in a night or a weekend, however large enough that you must make selections: the way to retailer the info, the way to break up the work into features, and what to do when the person sorts one thing surprising. That final query issues greater than novices anticipate, and each undertaking right here solutions it.
Construct and Run These Initiatives
Each undertaking is one .c file. With GCC or Clang (Linux, macOS, or Home windows with MSYS2 or WSL):
gcc -std=c11 -Wall -Wextra -o unit_converter unit_converter.c
./unit_converter
With Visible Studio, open a Developer Command Immediate and run:
cl /W4 unit_converter.c
unit_converter.exe
-Wall -Wextra (or /W4) activates the warnings that catch most newbie errors, so preserve them on. Every undertaking folder additionally comprises a checks/ folder with a pattern enter file. Operating ./unit_converter < checks/session.txt feeds the entire session to this system directly, which is how the repository checks each program routinely.
All 15 C Mini Initiatives at a Look
| # | Challenge | Stage | What you follow | Supply code |
|---|---|---|---|---|
| 1 | Unit Converter | 1 | Menu loops, features, lookup tables, secure quantity enter | unit_converter.c |
| 2 | Revenue and Loss Calculator | 1 | Arithmetic, if/else, percentages, formatted output |
profit_loss_calculator.c |
| 3 | Hangman | 1 | Strings, arrays listed by letter, argc/argv |
hangman.c |
| 4 | Swat the Fly | 1 | Your individual random generator, uint32_t, pointers, arrays |
swat_the_fly.c |
| 5 | Grade Report | 1 | Arrays, averages, highest and lowest marks, letter grades | grade_report.c |
| 6 | Balloon Shooter | 2 | Structs, an array of structs, enum, a recreation loop |
balloon_shooter.c |
| 7 | Sliding Quantity Puzzle | 2 | 2D arrays in a struct, Fisher–Yates shuffle, solvability | sliding_puzzle.c |
| 8 | Fly Away: Airport Textual content Journey | 2 | Enums, designated initializers, parsing instructions, a recreation loop | fly_away_adventure.c |
| 9 | Mini Piano | 2 | Word frequencies with pow, sine waves, binary information (WAV) |
mini_piano.c |
| 10 | Private Diary | 2 | Textual content information, append mode, dates with time.h, looking |
personal_diary.c |
| 11 | Handle E book | 3 | Arrays of structs, CSV information, search and kind | address_book.c |
| 12 | Birthday Reminder | 3 | Date arithmetic, sorting by subsequent incidence | birthday_reminder.c |
| 13 | To-Do Organizer | 3 | malloc and realloc, a rising array, save and cargo |
todo_organizer.c |
| 14 | Library Administration System | 3 | Associated structs, problem and return, due dates, information | library_management.c |
| 15 | Textual content Editor | 3 | Dynamic reminiscence, line buffers, command parsing | text_editor.c |
Stage 1: Your First C Initiatives
These 5 tasks want solely variables, loops, if/change, features, arrays and strings, plus a primary have a look at pointers in Swat the Fly. If in case you have completed a primary C course, begin right here.
1. Unit Converter in C
A menu-driven converter for on a regular basis models, and one of the best first undertaking on this set.
What you’ll construct: a program that converts size, mass, temperature and quantity. You decide a class, a “from” unit, a “to” unit and a worth, and this system prints the outcome and returns to the menu. For instance, 26.2 miles is 42.1648 km.
What you’ll follow:
- A menu loop that runs till the person quits
- Small features with one job every
- A lookup desk (an array of structs) as a substitute of a protracted
ifchain - Studying numbers safely with
fgetsandstrtod - Checking enter in opposition to real-world limits
The way it works: every unit is saved in a desk with its measurement in a single base unit per class, such because the metre for size. Changing is 2 steps: multiply into the bottom unit, then divide out of it. Eight models want eight numbers as a substitute of 56 separate formulation. Temperature is the exception, as a result of its scales begin at totally different zeros. It goes by Celsius as a substitute, and a worth under absolute zero (−273.15 °C) is rejected. Each quantity is learn as an entire line and checked earlier than it’s used, so typing abc, 12abc or 1e999 will get a well mannered “please enter a quantity” as a substitute of a crash or an infinite loop.
Particular notes:
- The conversion components are actual by definition, not rounded: the inch is strictly 0.0254 m and the pound precisely 0.45359237 kg. NIST lists them in its Information to the SI, Appendix B.
- Outcomes are printed with
%.6g, so 98.6 °F reveals as37 C, not37.000000 C. - Its enter features are reused, unchanged, by a lot of the later tasks.
Why convert by a base unit? As a result of the variety of formulation grows with each unit you add. With a base unit, including a brand new unit means including one row to the desk, and no different code adjustments.
Why not simply use scanf? When the person sorts letters, scanf("%lf", ...) fails and leaves them within the enter, so a loop that calls it once more fails endlessly. Studying a line with fgets and changing it with strtod lets this system verify precisely the place the quantity ended.
Supply code: unit_converter.c on GitHub
2. Revenue and Loss Calculator in C
A small enterprise calculator that will get cash proper to the cent.
What you’ll construct: a calculator that works out the revenue or loss on a sale, the promoting value wanted for a goal revenue, and the break-even amount, which is what number of models should be bought to cowl the mounted prices.
What you’ll follow:
if/else if/elsewith three outcomes- Storing cash as entire cents in a
lengthy lengthy - Turning textual content right into a quantity by hand, one digit at a time
- Guarding each division in opposition to zero
- The distinction between markup and margin
- Integer ceiling division
The way it works: each quantity is saved as an entire variety of cents, so 12.50 turns into 1250, and all totals are actual integer arithmetic. A customized parser accepts precisely what a value appears like: digits, then optionally a dot and one or two extra. So 12.345, -5 and 1,250 are rejected as a substitute of being silently rounded. The revenue report reveals two percentages for a similar revenue, markup on value and margin on promoting value. Break-even divides the mounted prices by what every unit earns and rounds up, as a result of promoting 333.33 models shouldn’t be potential.
Particular notes:
- A revenue of 250.00 on prices of 1250.00 is a 20% markup however solely a 16.67% margin. Mixing the 2 up is likely one of the commonest errors in revenue and loss issues.
- With mounted prices of 5000.00 and 15.00 earned per unit, the reply is 334 models: 333 falls simply quick.
- The most important allowed quantity instances the biggest amount nonetheless matches in a
lengthy lengthy, so no complete can overflow.
Why retailer cash in cents? A double can’t maintain most decimal fractions precisely: including 0.10 ten instances provides 0.99999999999999989, not 1. Entire cents add and multiply precisely.
Why are markup and margin totally different? They divide the identical revenue by totally different quantities: markup by the price, margin by the promoting value. The promoting value is bigger, so the margin is at all times the smaller proportion.
Supply code: profit_loss_calculator.c on GitHub
3. Hangman Sport in C
The traditional phrase recreation, and a pleasant introduction to strings in C.
What you’ll construct: a recreation that picks a secret phrase and reveals a clean for every letter. You guess one letter at a time; appropriate letters are crammed in, and every unsuitable one provides an element to the hanged man. Six unsuitable guesses lose the sport. Run it with --word and a pal can select the phrase.
What you’ll follow:
- Strings as arrays of
charthat finish in' ' - An array of 26
bools listed by letter - A desk of strings for the drawing
isalpha()andtoupper()with the forged they want- Command-line arguments with
argcandargv
The way it works: the key phrase is a string, and the sport retains one bool per letter of the alphabet to recollect which letters have been tried. letter - 'A' turns a letter right into a quantity from 0 to 25, so checking whether or not R has been guessed is a single array lookup. A repeated guess prices nothing. The gallows is rarely drawn with if statements: solely three rows of the image change, so they’re saved in a desk with one entry per variety of misses.
Particular notes:
- The guess is learn as an entire line and should be precisely one letter, so
ab,7and an empty line are rejected. letter - 'A'depends on A to Z having consecutive codes, which is true in ASCII. C itself solely ensures it for the digits'0'to'9'.
Why is there a --word choice? rand() might produce a distinct sequence on each C library, even with the identical seed. A set phrase lets a pal set the puzzle, and lets the repository’s checks replay precisely the identical recreation on Linux and Home windows.
Why forged to unsigned char earlier than isalpha()? On many programs char is signed, so a byte from an accented letter arrives as a detrimental quantity, and passing that to isalpha() is undefined behaviour. The forged makes it secure.
Supply code: hangman.c on GitHub
4. Swat the Fly Sport in C
A turn-based recreation of reminiscence and fast arithmetic, with a random quantity generator you write your self.
What you’ll construct: a fly sits on a wall of 9 spots. This system lists its hops, reminiscent of “proper, proper, left”, and also you swat the spot the place it landed. Successful scores a degree; a miss prices one in all three lives and reveals the fly’s actual path. Each around the fly hops as soon as extra.
What you’ll follow:
- Writing a small random quantity generator
uint32_tand unsigned arithmetic that wraps round- Passing values by pointer so a operate can change them
- Storing a path in an array and printing it again
- Checking a quantity given on the command line
The way it works: the random numbers come from a linear congruential generator, the identical formulation the C customary prints as its instance rand(). As a result of its state is a uint32_t, the arithmetic wraps the identical approach on each compiler. Every spherical attracts a begin spot and the hops, and shops each spot the fly visits. A hop that would go away the wall bounces again. The rating and lives dwell in essential(), and the spherical operate updates them by pointers.
Particular notes:
- The identical seed provides the identical recreation in every single place: video games 42 and seven produce equivalent fly paths with GCC, Clang and Visible Studio.
- The seed is checked rigorously, as a result of
strtoul()would fortunately settle for-1,+5or main areas. - The identical formulation seems within the POSIX specification of rand().
Why not use rand()? The C customary doesn’t say which sequence rand() produces, so the identical seed provides a distinct recreation on Linux and on Home windows. A generator you write your self behaves the identical in every single place, which makes the sport testable and lets two associates race on “recreation quantity 7”.
Why write (*rating)++ with parentheses? With out them, *rating++ strikes the pointer as a substitute of including to the rating. GCC and Clang each warn about it, which is another reason to maintain warnings on.
Supply code: swat_the_fly.c on GitHub
5. Scholar Grade Report in C
A report card for an entire class, constructed on two-dimensional arrays.
What you’ll construct: you enter the themes, the scholars and their marks. This system prints every pupil’s complete, common and letter grade, and every topic’s common, highest and lowest mark. It additionally prints the category common, the highest pupil and what number of college students bought every grade.
What you’ll follow:
- Two-dimensional arrays: one row per pupil, one column per topic
- A number of names saved in a 2D
chararray - Passing a 2D array to a operate
- The integer division entice
- Operating totals, highest and lowest values
- A lookup desk for letter grades, and lining up columns with
printfwidths
The way it works: all of the marks dwell in a single array, marks[student][subject]. The report card walks it row by row, one pupil at a time, and the topic statistics stroll it column by column, with the identical nested loop circled. Each common goes by one small operate that converts to double earlier than dividing. The letter grade comes from a brief desk of cut-offs (90, 80, 70, 60) as a substitute of a series of if statements, and >= makes precisely 90.00 an A.
Particular notes:
- When a 2D array is handed to a operate, the parameter should spell out the column measurement,
int marks[][MAX_SUBJECTS], so the compiler is aware of how far aside the rows are. - Topic names are restricted to 7 characters so each column retains an area between names.
Why does 275 / 3 give 91? Dividing one int by one other throws the fraction away earlier than the result’s saved. Changing one facet first, (double)complete / depend, retains the 91.67.
Why begin the very best and lowest on the first mark? A “lowest up to now” that begins at 0 by no means adjustments, as a result of no mark is under 0. Beginning each from the primary pupil’s mark makes each comparability significant.
Supply code: grade_report.c on GitHub
Stage 2: Structured Packages
These 5 tasks use struct and enum to explain the issues a program works with: balloons, a puzzle board, the rooms of an airport, notes and diary entries. Two of them additionally write information. Every program continues to be one file, however it’s organised round its knowledge as a substitute of round a single loop. If both key phrase is new, learn the guides to constructions in C and enum in C first.
6. Balloon Shooter Sport in C
A turn-based capturing recreation on a textual content grid, organised round structs.
What you’ll construct: balloons rise by an 8 × 8 sky: gradual ones (o) rise one row per flip, quick ones (O) two. Every flip you shoot one row, with 15 arrows for 12 balloons. Your arrow flies whereas the balloons rise, so you have to goal the place a balloon will likely be.
What you’ll follow:
- A
structfor one recreation object, and an array of them - A second
structthat holds the entire recreation, handed by pointer - An
enumfor the sport standing - A recreation loop: draw, learn enter, replace, verify
- Conserving the sport’s knowledge separate from the image on display screen
The way it works: every balloon is a struct with its row, column, velocity and an energetic flag, and the entire recreation lives in a single Sport struct. Each flip the loop attracts the sky, reads a row, strikes the balloons up, checks the shot and provides new balloons. The sky is rarely saved as characters: draw() builds a contemporary grid from the balloon array every flip, so the image can by no means disagree with the info.
Particular notes:
- With out a rule, a quick balloon catches up with a gradual one in the identical column. In a simulation of 6,000 video games with out it, 2,126 had two balloons in a single cell; with the rule, none of 9,000 did.
- Video games are seeded with the generator from Swat the Fly, so recreation 42 is identical on each pc.
Why are popped balloons marked inactive as a substitute of eliminated? Eradicating a component from the center of an array means shifting every thing after it. Flipping a bool is one project, and each loop merely skips inactive balloons.
Why just one balloon per column? Balloons solely transfer up, so balloons in numerous columns can by no means meet. A brand new balloon solely seems in an empty column, which makes the “two balloons in a single cell” bug unattainable as a substitute of dealing with it in code.
Supply code: balloon_shooter.c on GitHub
7. Sliding Quantity Puzzle (15-Puzzle) in C
The traditional sliding-tile puzzle, and a lesson in why a good shuffle wants some arithmetic.
What you’ll construct: a 3 × 3 (8-puzzle) or 4 × 4 (15-puzzle) board of numbered tiles with one hole. You slide tiles into the hole till they’re so as, and this system counts your strikes. A straightforward stage and a tough stage shuffle the board in numerous methods.
What you’ll follow:
- A 2D array inside a struct
- Treating a 2D board as a 1D record with
/and% - The Fisher–Yates shuffle
- Counting inversions with nested loops
- Checking {that a} transfer is authorized
The way it works: the board is a 2D array, however shuffling and counting are simpler on a flat record. Cell quantity i is at row i / measurement and column i % measurement. The straightforward stage begins from the solved board and makes 20 random authorized slides, so it’s at all times solvable. The onerous stage shuffles each tile with Fisher–Yates, then counts inversions (pairs of tiles within the unsuitable order) to resolve whether or not the board will be solved. If it can’t, swapping two tiles fixes it.
Particular notes:
- For the 8-puzzle, precisely 181,440 of the 362,880 potential preparations will be solved. A search of each reachable place confirms it.
- On a 3 × 3 board, a board is solvable when the variety of inversions is even; on a 4 × 4 board, the hole’s row additionally counts.
Why can half of all shuffles not be solved? On a 3 × 3 board, sliding a tile by no means adjustments whether or not the inversion depend is even or odd, and the solved board has an excellent depend (on a 4 × 4 board the hole’s row is a part of the identical rule). Swapping two tiles at all times flips it, which is why one swap strikes a board into the solvable half.
Why Fisher–Yates? It provides each association precisely the identical likelihood. Easier “swap random pairs” shuffles favour some preparations over others.
Supply code: sliding_puzzle.c on GitHub
8. Fly Away: A Textual content Journey Sport in C
A brief textual content journey set in an airport, the place each transfer prices a minute.
What you’ll construct: your flight leaves in quarter-hour. You kind instructions reminiscent of n, take passport and board to get from the taxi drop-off to the appropriate gate, previous check-in, safety and a gate change. Trying round and checking your bag are free; a espresso prices three minutes.
What you’ll follow:
- An
enumfor each set of names: rooms, instructions, objects, instructions - A struct that holds the entire recreation
- A map saved as knowledge with designated initializers
- Splitting a line right into a verb and a noun
- Evaluating phrases with
strcmp - A recreation loop with one place the place time is spent
The way it works: the seven locations are rows of a desk, and every row says which room lies north, south, east and west. The desk is crammed in by identify with designated initializers, reminiscent of [CHECK_IN] = {...}. Transferring is then a single lookup. Every command is trimmed, lowercased and break up right into a verb and a noun. Each handler returns what it value, and the primary loop subtracts that in precisely one place, then checks the clock.
Particular notes:
- The shortest profitable route takes 8 minutes, so the absolute best end leaves 7 to spare. A search of each reachable recreation state confirms it.
- Boarding in your final minute nonetheless wins, as a result of the clock is checked after the sport has been received.
Why evaluate phrases with strcmp and never ==? line == "take" compiles, however it compares the addresses of two strings, not their letters, so it’s nearly by no means true. The information to evaluating strings in C covers the alternate options.
Why retailer the map as a desk? Including a room means including one row, not writing extra if statements. And any exit not listed is routinely “nowhere”, as a result of the primary enum worth is 0.
Supply code: fly_away_adventure.c on GitHub
9. Mini Piano in C (Write a WAV File)
A program that turns typed notes right into a sound file you may play, utilizing no sound library in any respect.
What you’ll construct: you kind a tune reminiscent of C4 E4 G4 C5, select how lengthy every observe lasts, and this system writes a WAV file that any media participant opens. Sort ode to load the opening of Beethoven’s Ode to Pleasure.
What you’ll follow:
- Turning observe names into frequencies with
pow() - Making a sound wave with
sin(), pattern by pattern - Writing a binary file with
"wb" - Little-endian numbers and a set file header
- Splitting a line into phrases with
strtok()
The way it works: every observe identify turns into a MIDI observe quantity (C4 is 60, A4 is 69), and the frequency is 440 × 2 to the facility (n − 69) / 12, so C4 is 261.63 Hz. Every observe is a sine wave of twenty-two,050 samples per second, scaled to 30% quantity, with a ten ms fade out and in to keep away from clicks. The file begins with a 44-byte header that describes the format, written one byte at a time, lowest byte first. Then come the samples as 16-bit numbers.
Particular notes:
- Six notes of 400 ms make a file of precisely 105,884 bytes: 6 × 8,820 samples × 2 bytes, plus the header.
- On Linux, add
-lmafter the supply file, or the linker can’t discoversinandpow. - The identical
tune.wavgot here out byte-identical from GCC on Linux and from Visible Studio on Home windows.
Why does the file want "wb"? On Home windows, textual content mode turns each byte with the worth 10 into two bytes. Sound knowledge comprises that worth by likelihood, so tune.wav grew by 562 bytes and each pattern after the primary further byte was misaligned. On Linux the 2 modes are the identical, so the bug hides till somebody runs this system on Home windows.
Why write the bytes one by one? A WAV file is little-endian on each pc, however fwrite of a quantity or a struct makes use of the pc’s personal byte order and will embrace padding. Writing every byte explicitly produces the identical file in every single place.
Supply code: mini_piano.c on GitHub
10. Private Diary in C
A diary stored in a plain textual content file: the primary undertaking whose knowledge survives after this system ends.
What you’ll construct: you write an entry, and this system stamps it with right now’s date and provides it to the file. You may record each entry or search them for a phrase, ignoring case. Shut this system, run it once more tomorrow, and yesterday’s entries are nonetheless there.
What you’ll follow:
- File modes:
"a"to append,"r"to learn - Treating a lacking file as an empty diary (
errno == ENOENT) - Studying a textual content file line by line with
fgets - Right now’s date with
time(),localtime()andstrftime() - Checking a date by hand, together with the leap-year rule
- A case-insensitive search written by hand
The way it works: every entry is one line of the file, reminiscent of 2026-12-01 | Began the C mini tasks.. Writing opens the file in append mode and provides one line. Studying opens it with "r". A lacking file merely means an empty diary, whereas every other error is reported. Every line is break up on the first " | " with out copying something: the separator is overwritten with ' ', so one buffer holds each the date and the textual content. Search outcomes preserve their numbers from the complete record. The information to file dealing with in C covers each file mode.
Particular notes:
- The leap-year rule has three elements: 2024 and 2000 are leap years, 1900 shouldn’t be.
--today 2026-12-01replaces the clock, so the checks give the identical outcome on any day.- A line edited by hand to be longer than 319 characters can be break up in two; Challenge 13 reveals the way to learn traces of any size.
Why "a" and never "w"? "w" empties an present file the second it opens it, so each new entry would erase the entire diary. "a" at all times provides to the top.
Why write your individual case-insensitive search? The C library has no customary one: strcasestr exists on Linux and macOS, however not in customary C or on Home windows. Two nested loops with tolower() do the job anyplace.
Supply code: personal_diary.c on GitHub
Stage 3: Small Functions
These 5 tasks are small purposes. Each retains its knowledge in a file between runs, checks what it masses, and saves by a short lived file, so a failed write by no means damages the file you already had. Two new concepts arrive right here: dynamic reminiscence (malloc, realloc and free) within the To-Do Organizer, and data that refer to one another by ID within the Library Administration System. The Textual content Editor brings every thing collectively.
The applications are longer, from about 600 to 900 traces, however 15 to 24 % of every file is features copied unchanged from earlier tasks: the enter helpers from Challenge 1, the date checks from the diary, the case-insensitive comparability from the tackle e book. Reusing examined code as a substitute of rewriting it’s how actual applications develop.
11. Handle E book in C
An tackle e book saved in a CSV file that Excel, LibreOffice or any textual content editor can open.
What you’ll construct: a contact record with a reputation, cellphone quantity and e-mail for every individual. You may record contacts by identify or by e-mail, add, search and delete them, and save. In case you give up with unsaved adjustments, this system asks first. Names reminiscent of Smith, John or Ana "Ani" Lopez survive the journey to the file and again.
What you’ll follow:
- An array of structs stored in sorted order
qsort()with your individual comparability features- Evaluating strings whereas ignoring case
- Copying an entire struct with
= - Deleting from an array with
memmove() - Studying and writing CSV accurately
- A secure save and an “unsaved adjustments” flag
The way it works: the contacts are stored sorted by identify with qsort, which takes your comparability operate as an argument and calls it each time it must order two contacts. The e-mail record kinds a replica, so the numbers utilized by Delete by no means change. CSV fields that comprise a comma or a quote are written inside double quotes, with each quote doubled, the rule in RFC 4180. The reader understands the identical rule. Saving writes a short lived file first after which replaces the outdated one, so a failed write by no means damages the prevailing file.
Particular notes:
- Unhealthy traces in a hand-edited file are skipped and counted, by no means deadly: a unsuitable variety of fields, an unclosed quote, an invalid cellphone or e-mail, or a reproduction identify.
- 5,000 random contacts filled with commas and quotes have been written and browse again unchanged, and each line matched Python’s personal CSV author.
Why does strcmp type “Smith” earlier than “ben”? It compares character codes, and in ASCII each uppercase letter comes earlier than each lowercase one. Lowercasing each letters earlier than evaluating places names within the order a reader expects.
Why memmove and never memcpy to delete? Deleting shifts the later contacts down by one place, so the supply and vacation spot overlap. memmove handles overlapping reminiscence; with memcpy the result’s undefined.
Supply code: address_book.c on GitHub
12. Birthday Reminder in C
A birthday record that greets you with the birthdays developing this week.
What you’ll construct: a program that retains names and beginning dates in a textual content file. At start-up it reveals whose birthday is right now or within the subsequent 7 days, and the complete record reveals everybody soonest first, with the age they’re about to show. You may add and delete folks, and each change is saved immediately.
What you’ll follow:
- A
Datestruct handed and returned by worth - Day-of-year and days-between arithmetic with no library date features
- A particular rule for 29 February
- Sorting by a worth this system calculates
- Breaking ties with a second comparability
The way it works: for every individual, this system works out the subsequent birthday: this yr’s date, or subsequent yr’s if it has handed. It then counts the times till it with whole-day integer arithmetic. As a result of the subsequent birthday is rarely greater than a yr away, two circumstances cowl every thing: the identical yr, or the remainder of this yr plus a part of the subsequent. The times-away worth is calculated as soon as per individual, the record is sorted by it with qsort, and ties are damaged by identify, ignoring case.
Particular notes:
- Individuals born on 29 February have fun on 28 February when the yr shouldn’t be a bissextile year. The rule lives in a single small operate, so altering it to 1 March is a one-line edit.
- The date arithmetic was checked in opposition to Python’s calendar for seven beginning dates on day by day from 2000 to 2400.
- The order of the saved record doesn’t matter, so deleting an individual strikes the final individual into the hole as a substitute of shifting everybody down.
Why not use mktime()? It really works in native time, so a daylight-saving change could make a “day” 23 or 25 hours lengthy, and dividing seconds by 86,400 will be off by one. Counting entire days provides the identical reply on each pc.
Why calculate the type key earlier than sorting? qsort calls the comparability operate many instances for every component. Figuring out a birthday inside it could repeat the identical date arithmetic time and again.
Supply code: birthday_reminder.c on GitHub
13. To-Do Record Organizer in C
A to-do record with priorities and due dates, and the primary undertaking with dynamic reminiscence.
What you’ll construct: a activity record saved to a textual content file after each change. Every activity has a precedence (excessive, medium or low), an elective due date and a carried out mark. The record reveals unfinished duties first, then by precedence and due date, and marks something overdue or due right now. Not like each earlier program, it has no mounted restrict on the variety of duties or their size.
What you’ll follow:
malloc,reallocandfree- A rising array: a pointer, a depend and a capability
- Studying a line of any size
- Sorting an array of pointers with
qsort - Eradicating many components in a single move
- Proving there aren’t any reminiscence leaks
The way it works: the duties dwell in an array that begins with room for 4 and doubles (8, 16, 32…) each time it fills. Every activity’s textual content is its personal malloced copy, sized precisely. To record the duties, this system kinds a separate array of pointers to them, so every activity retains its place, which is the quantity you kind to mark or delete it. A file line of any size is learn right into a buffer that begins at 16 bytes and doubles as wanted. Each malloc has precisely one free. See malloc vs calloc in C for the allocation features themselves.
Particular notes:
YYYY-MM-DDdates type accurately as plain textual content, sostrcmpin opposition to right now’s date decides “overdue”.- Eradicating one
freename and operating the checks below AddressSanitizer stories 236 bytes leaked in 4 allocations, and the check fails. Compile with-g -fsanitize=tackleto verify your individual applications the identical approach. strdup()solely grew to become customary C in C23, so this system makes use of its personal four-line copy operate.
Why put the realloc lead to a short lived pointer? If realloc fails it returns NULL however the outdated array continues to be there. Writing objects = realloc(objects, ...) would overwrite the one pointer to it: the duties can be misplaced and the reminiscence leaked.
Why type pointers as a substitute of the duties? Every activity’s place is the quantity the person sorts, so the duties themselves should not transfer. Sorting a short lived array of pointers adjustments solely the show order.
Supply code: todo_organizer.c on GitHub
14. Library Administration System in C
A library desk program with three sorts of file that refer to one another.
What you’ll construct: a system of books, members and loans. You may add books and members, problem a e book for 14 days, and take it again, with a effective of 0.25 for every day late. A report lists every thing on mortgage, soonest due first. All three sorts of file dwell in a single textual content file, one per line, every marked with a letter: B, M or L.
What you’ll follow:
- Structs that refer to one another by ID
- Trying data up by ID
- Values which can be counted, not saved
- Guidelines that preserve linked knowledge constant
- Date arithmetic throughout months and years
- Cash in entire cents
The way it works: a mortgage shops solely a e book ID and a member ID, like a row in a database desk, and this system appears up the title and identify when it prints. The variety of copies on the shelf is rarely saved; it’s counted from the loans each time. Issuing checks that the e book and the member exist, that the member has fewer than 3 books and never this one already, and {that a} copy is free. After loading the file, this system drops any mortgage that breaks these guidelines, so a hand-edited file can’t corrupt the info.
Particular notes:
- A due date can cross a month or yr: 2026-12-20 plus 14 days is 2027-01-03. Turning every date right into a day quantity makes the times between two dates one subtraction.
- A member with books on mortgage can’t be eliminated, or their loans would level at no person.
- The date features have been checked in opposition to Python’s calendar for each date from 1900 to 2400.
Why hyperlink data by ID and never by identify or pointer? A duplicate of a reputation goes stale when the identify is corrected, and a pointer into an array factors on the unsuitable file after an earlier one is eliminated. An ID stays legitimate and will be written to a file.
Why depend obtainable copies as a substitute of storing them? A saved depend is unsuitable endlessly if one code path forgets to replace it. Counting from the loans takes microseconds and is at all times proper.
Supply code: library_management.c on GitHub
15. Textual content Editor in C
A working line editor in customary C, which brings each earlier concept collectively.
What you’ll construct: an editor that opens a file, or begins a brand new one, and edits it with quick instructions:
pprints traces;aprovides traces after any line;cadjustments a line;ddeletes;ffinds a phrase;rreplaces textual content in every single place;wsaves, andqquits.
The immediate adjustments to edit*> whereas there are unsaved adjustments, and quitting asks earlier than throwing them away. Strains will be any size, and indentation is stored precisely.
What you’ll follow:
- Textual content saved as an array of tips to strings,
char ** - Inserting and deleting in the midst of a dynamic array
- Constructing a brand new string of precisely the appropriate measurement
- Parsing instructions with elective line numbers
- Studying traces of any size, from a file and from the keyboard
- An unsaved-changes flag and “save as”
The way it works: the file is held as an array of pointers, one per line, every pointing to its personal malloced string. Inserting or deleting a line strikes solely pointers, by no means the textual content. Substitute builds every modified line in two passes: depend the matches, allocate precisely the appropriate measurement as soon as, then copy the items. Typed traces are learn with the identical any-length line reader because the file, as a result of the keyboard (stdin) is a FILE * too. Each command’s line numbers are checked in opposition to the present file earlier than they’re used.
Particular notes:
- This can be a line editor, like Unix
ed, the editor that got here earlier than full-screen editors reminiscent of vi. It wants no cursor keys or display screen management, so it runs in any terminal. - Discover (
f) ignores case; exchange (r) matches precisely, and the assistance textual content says so. - 2,000 random modifying classes matched an impartial mannequin of each command, with no reminiscence errors or leaks.
Why retailer the textual content as an array of traces? Inserting a line right into a 100,000-line file strikes 99,999 pointers, 8 bytes every, nonetheless lengthy the traces are. In a single large string, each character after the insertion level must transfer.
Why does exchange want two passes? The brand new line’s measurement should be recognized earlier than the malloc, and it relies on what number of matches there are. So the primary move counts and the second copies.
Supply code: text_editor.c on GitHub
5 Errors Rookies Make in These Initiatives
Each one in all these errors seems in C tasks that college students hand in, and each one has a undertaking above that reveals the repair.
1. Studying enter with scanf and trusting it. scanf("%d", &n) stops on the first character that isn’t a part of a quantity and leaves it within the enter. Sort abc right into a loop that calls it once more, and it fails once more, endlessly. scanf("%s", identify) is worse: it shops the entire phrase the person sorts, even previous the top of the array. Repair: learn an entire line with fgets, then convert it with strtol or strtod and verify the place the quantity ended, as read_int() and read_double() do within the Unit Converter.
2. Evaluating strings with ==. if (command == "give up") compiles, however it compares two addresses, not two phrases, and is nearly by no means true. Repair: strcmp(command, "give up") == 0, as within the parser of Fly Away. To disregard case, write a small comparability loop with tolower, because the Handle E book does, as a result of strcasecmp shouldn’t be customary C.
3. Dividing two integers and anticipating a fraction. 275 / 3 is 91 in C, not 91.67. The fraction is thrown away earlier than the result’s ever saved in a double. Repair: convert one facet first, (double)complete / depend, and do it in a single operate so it can’t be forgotten, because the Grade Report does.
4. Opening a file within the unsuitable mode. "w" empties an present file the second it opens, which might erase the Private Diary on each entry; including to a file wants "a". And on Home windows, textual content mode turns each byte with the worth 10 into two bytes. The Mini Piano‘s WAV file grew by 562 bytes that approach, misaligning each pattern after the primary further byte. Repair: "a" so as to add, "w" solely to interchange, and "rb"/"wb" for something that isn’t textual content.
5. Dropping observe of reminiscence. Writing objects = realloc(objects, measurement) loses the one pointer to the outdated array if realloc fails, and forgetting a single free leaks reminiscence each time this system runs. Repair: put the realloc lead to a short lived pointer first, give each malloc precisely one free, and verify with AddressSanitizer (-fsanitize=tackle), which stories leaks on Linux. The To-Do Organizer reveals all three.
Larger C Initiatives to Strive Subsequent
As soon as these 15 really feel snug, the subsequent step is applications with extra shifting elements: real-time enter, bigger knowledge constructions, or an entire recreation loop. These guides on MYCPLUS every construct one full program in trendy, customary C or C++:
- Sample applications in C: nested loops, practised on star, quantity and alphabet patterns. A very good warm-up if Stage 1 felt onerous.
- Snake recreation in C: a real-time recreation within the terminal: this system retains shifting whereas it waits in your keys.
- Brick breaker recreation in C: a 2D array of bricks, collision guidelines and a recreation loop, one step past the Balloon Shooter.
- Linked record in C: a listing that grows one node at a time, the pure subsequent step after the rising arrays of Initiatives 13 and 15.
- Automotive race recreation in C++: the identical type of recreation written with lessons, for once you transfer on to C++.
- Financial institution administration system in C: accounts, transfers and month-to-month curiosity throughout seven supply information, with cash stored in entire cents and a ledger this system checks on each begin. The subsequent step up from the file keepers in Initiatives 11 to 14.
Key Takeaways
- A mini undertaking in C is a small, full program that solves one actual activity. These 15 run from 231 to 869 traces, all in customary C, so each builds with a single command on GCC, Clang or Visible Studio.
- Work by the three ranges so as. Stage 1 practises loops, features, arrays and strings. Stage 2 organises applications round
structandenum. Stage 3 provides information that persist, dynamic reminiscence and linked data. - Validate each enter. Learn entire traces with
fgets, convert them withstrtolorstrtod, and verify the outcome. Nearly each undertaking depends on that one behavior. - Choose knowledge to code. Lookup tables, a room map constructed with designated initializers, and values counted from data as a substitute of saved all take away entire lessons of bugs.
- Reuse examined features. The later tasks copy the enter helpers, date checks and line reader unchanged, which is how actual applications develop.
- Let instruments verify your work. Compile with
-Wall -Wextra(or/W4), and run AddressSanitizer to catch reminiscence errors and leaks earlier than your customers do.
Continuously Requested Questions
Conclusion
These 15 tasks take you from a menu-driven converter to a working textual content editor, one concept at a time. Alongside the way in which they cowl the elements of C that matter in actual applications: enter that can’t crash this system, knowledge organised in structs, information that preserve their contents, and reminiscence that’s at all times freed. Each is sufficiently small to learn in a night, and each one is examined on Linux and Home windows.
Decide the undertaking that matches what you already know right now, construct it, then change it: the Do that subsequent concepts are the place the true studying occurs. When you’re prepared for extra, the C programming part has guides to each subject these tasks use.
Supply Code and Checks
All applications on this web page are within the mini-projects listing of the MYCPLUS C examples repository, one folder per undertaking.
Construct and check all of them:
cmake -S . -B construct
cmake --build construct
ctest --test-dir construct --output-on-failure
What the construct checks. Each program is compiled with GCC and Clang below C11 and C17 with -Wall -Wextra -pedantic -Werror, and with Visible Studio (MSVC) below /W4 /WX, so a single warning fails the construct. Every undertaking’s pattern classes are fed to this system, and its output is in contrast character by character with the anticipated output (line endings apart). The identical classes additionally run below AddressSanitizer and UndefinedBehaviorSanitizer. There are 48 session checks in all, run in seven configurations (4 on Linux, one sanitizer construct, two on Home windows): 336 check runs on each change, all passing.
What I Verified
Each program, output and quantity on this web page was checked, not simply written.
| Test | Ubuntu 24.04 (GCC 13.3, Clang 18.1) | Home windows 11 (Visible Studio 2022) |
|---|---|---|
| Builds with zero warnings | GCC and Clang, C11 and C17, -Wall -Wextra -pedantic -Werror |
MSVC /W4 /WX, C11 and C17 |
| Session checks (48 in all) | 48/48 in every of the 4 builds | 48/48 in each builds |
| Reminiscence errors and leaks | AddressSanitizer, UndefinedBehaviorSanitizer and LeakSanitizer: 48/48 clear | Not obtainable in these builds |
| Similar outcomes on each programs | Mounted-seed video games, WAV information and dates give equivalent output | Equivalent anticipated information move |
Past the checks, the trickier logic was checked in opposition to impartial fashions written in Python:
- Video games: 6,000 random video games of Fly Away, 300 Balloon Shooter video games and 800 sliding-puzzle boards.
- Puzzle maths: the solvability rule, checked in opposition to all 362,880 boards of the 8-puzzle.
- Mini Piano: each WAV information, rebuilt byte for byte.
- Dates: each date from 1600 to 2400 for the diary, and day by day from 2000 to 2400 for the birthday reminder and from 1900 to 2400 for the library’s due dates.
- Handle E book: 5,000 random CSV data with commas and quotes, learn again with Python’s personal CSV module.
- Textual content Editor: 2,000 random modifying classes, in contrast with a mannequin of each command.
All of them agreed.

