Back to Explore
GuideVibeFix editorialUpdated Nov 25, 2026

Writing C from Zero: First Program, Type Sizes, and a Book-List Mini-Project

GCC 13.3.0, C17, zero packages: a first C program, sizeof results 1/2/4/8/8/4/8/8, sum 1..100 is 5050, 10! is 3628800, 8 numbers sorted, 3 books total 1088 pages, 3 file lines and 70 chars read back. Preprocessing alone expands 3 lines to 815.

Real photograph of a programmer working at monitors full of code in a dim office (illustrative photo)

If you have written Python or JavaScript, your first look at C may feel terse: no one-line print that just works, no list comprehensions, and even strings need you to mind their length. But C is worth learning for one reason: it is the mainstream language closest to the machine. Operating systems, databases, embedded devices, and the low levels of game engines are still C or close relatives of C. Learn C and you learn how programs actually run on a machine.

This guide has a concrete goal: start from zero, write a first C program that compiles and runs, understand how many bytes each type takes, how loops and arrays work, what structs and pointers are, and tie it all together in a small three-book project. All code was really run on this machine: GCC 13.3.0, the C17 standard, zero third-party packages. The demo program and its transcripts are in the draft folder, and every number in this article matches them.

Check the environment first. Open a terminal, type gcc --version, and if you see something like gcc (Ubuntu 13.3.0), the compiler is installed. The first line shows version 13.3.0. There is no "installing" step for C itself: you write a .c text file, the compiler turns it into an executable, and running the executable produces output. Write, compile, run — that is the whole C workflow.

The first program is five lines. Create hello.c, write #include <stdio.h>, then a main function with one line: printf("Hello, C!\n");. Compile it with gcc -o hello hello.c. Run it with ./hello. When "Hello, C!" appears on screen, your first C program works. Three things to remember: #include copies in the standard library's declarations, main is the program's entry point, and \n in printf is a newline. Without \n, the next output continues on the same line.

Section 1 of the demo program is exactly that line of output. Running ./demo253_g1 en prints "[Section 1] Hello, C" and then "Hello, C! This is the first line a C program prints." Section 2 measures how many bytes each type takes, using the sizeof operator. sizeof is not a function, it is an operator: sizeof(int) gives you the byte count of an int. On this 64-bit Linux machine with GCC 13.3.0, the measured results are: char 1 byte, short 2 bytes, int 4 bytes, long 8 bytes, long long 8 bytes, float 4 bytes, double 8 bytes, and pointer void* 8 bytes.

Three of those numbers are the ones to remember: char is always 1, int is 4 on today's mainstream platforms, and a pointer is 8 on a 64-bit machine. long is the trap: on 64-bit Linux it is 8 bytes, on 64-bit Windows it is 4 bytes. When writing cross-platform code, never assume the size of long; measure it with sizeof, or use fixed-width types such as int32_t and int64_t directly. Fixed-width types live in stdint.h, and you will meet them sooner or later in C.

Section 3 is loops. The demo computes three numbers: the sum of 1 to 100 is 5050, 10 factorial is 3628800, and 2 to the power of 10 is 1024. The 5050 has a small story behind it: as a child, Gauss paired the numbers — 1 plus 100 is 101, 2 plus 99 is 101 — 50 pairs, giving 5050. A loop is that idea translated into code: for (int i = 1; i <= 100; i++) sum += i;. The three parts inside the for parentheses are the start, the continue condition, and what happens after each round. The factorial loop is the same shape, only the accumulation changes from addition to multiplication.

One detail matters here: is 10 factorial, 3628800, already past the safe range of int? No. An int is 32 bits with a maximum of 2147483647, and 3628800 is far below it. But 13 factorial is 6227020800, past the int maximum — stored in an int it overflows and becomes a negative number or a wrong number. The demo stores the factorial in a long, which is 64 bits on this machine with a maximum around 9.22 times 10 to the 18th; 20 factorial is 2432902008176640000 and just fits, while 21 factorial does not. Picking a type too small overflows, picking one too big wastes space — that trade-off is a daily decision in C.

Section 4 is arrays and sorting. The demo holds 8 numbers: 7, 3, 9, 1, 8, 2, 6, 4. Sorting uses bubble sort: compare neighbors, push the larger one back, and after one pass the largest number has sunk to the end; repeat. Sorted, the array reads 1, 2, 3, 4, 6, 7, 8, 9. The element sum is 40, the maximum is 9, the minimum is 1. Bubble sort is slow — 8 numbers need 28 comparisons — but it is the easiest sorting algorithm to explain, and everyone starts there.

Arrays in C have one defining trait: the array name is the address of its first element. The demo writes int *p = &a[0];, then prints a[0] and *p, and both are 1. p is a pointer holding the address of a[0], and *p means "go to that address and fetch the number." Pointers are the hardest and most central idea in C; on first meeting, remember one sentence: a pointer is an address, and the asterisk means "fetch what lives at that address." The relationship between arrays and pointers is the first step into C's memory model.

The most common pointer pitfall is going out of bounds. An array of 8 numbers has indices 0 through 7; a[8] is out of bounds. C will not stop you: a[8] can be read and written, reading whatever memory happens to sit after the array, and writing there may overwrite another variable. The compiler does not complain, and the program may not crash immediately — it keeps running with wrong data and fails somewhere entirely unrelated. The first discipline of writing C is this: count your own indices, because the compiler will not count them for you.

Section 5 is structs. The demo defines a struct Book with two fields, title and pages, then stores three books: C Primer with 320 pages, C Traps with 256, C Pocket with 512. The three books total 1088 pages, averaging 362.67 pages. A struct is C's way of packing several related pieces of data into one shape. Without it you would keep three separate arrays for titles and page counts, and they would drift apart. A struct gives data a shape.

Note how the average of 362.67 is computed: total pages 1088 divided by 3. In C, an integer divided by an integer gives an integer, so 1088 / 3 is 362 and the remainder is dropped. The demo writes total / 3.0, and with the denominator as 3.0 the division becomes floating-point, giving 362.67. The classic beginner mistake is writing total / 3 and wondering why the average has no decimal point. Remember: if you want decimals, at least one side of the division must be floating-point.

Section 6 is file I/O. The demo writes 3 lines into notes253.txt, reads them back, and counts 3 lines and 70 characters in total. Writing opens with fopen("notes253.txt", "w"), reading with fopen("notes253.txt", "r"), and both need fclose when done. The "w" mode writes and clears existing content; the "r" mode reads, and returns a null pointer if the file does not exist. The demo does not check for a null pointer; real code must: if fopen fails and you do not handle it, the fgets that follows will crash.

Where does the 70 come from? The three lines are "C is small and fast.\n" (22 characters including the newline), "sizeof(int) is 4 here.\n" (24), and "1 + 2 + ... + 100 = 5050.\n" (24); 22 plus 24 plus 24 is 70. The newline \n counts as a character too. When counting file sizes, the newline is the character most often forgotten — remember that it counts.

The compile command deserves its own paragraph. The demo is built with gcc -Wall -Wextra -O2 -std=c17 -o demo253_g1 demo253_g1.c. -Wall and -Wextra turn on warnings, -O2 is second-level optimization, -std=c17 compiles against the C17 standard, and -o names the output file. Without -o the output is called a.out by default. The name -Wall is misleading: it is not "all warnings," only the common ones, and -Wextra adds another batch. The habit to build in C is: warnings fully on, and treat warnings as bugs to fix. Many C bugs are already pointed out by the compiler in a warning — you just have to read it.

Try compiling once without -Wall: nothing changes. Then try a classic mistake in the code, such as writing if (x = 1) where you meant a comparison, and -Wall warns you at once. In C, an assignment inside an if is legal, so the compiler will not error — it will only warn. That is the difference between a warning and an error: an error means the compiler refuses to compile, a warning means it compiles but you should take a look. The beginner's rule should be: zero warnings before you run anything.

Then there are header files. The demo's first line is #include <stdio.h>, the standard input/output library, home of printf, fopen, and fgets. #include pastes the header's contents into your source file verbatim, so the compiler sees printf's declaration and knows what arguments it takes and what it returns. Your own functions follow the same rule: declare before use, or define before use. C reads top to bottom, and the compiler cannot use a name it has not seen.

Strings in C are a special case. The demo stores a book title as char title[32], an array of 32 characters. C has no real string type: a string is a character array ending in '\0'. title[32] holds 31 visible characters plus the terminating '\0'. Writing a title longer than 31 characters overflows into neighboring memory. The string functions strcpy and strcat never check length — this is where most of C's historical security vulnerabilities come from. The modern habit is strncpy or snprintf, and always leaving one slot for '\0'.

Memory management is the biggest difference between C and Python or JavaScript. In Python you create objects and the garbage collector takes away the ones you no longer need; in C there is no garbage collector, and memory from malloc must be freed by hand. The demo never calls malloc: every variable lives on the stack and is reclaimed automatically when its function returns. That is the most comfortable way to start: no malloc means no leaks and no double frees. When malloc arrives, learn it then — do not reverse the order.

Debugging C has one crude method that works best: add printf at key points. When the program crashes, look at the last line it printed, then narrow the range below it. A more professional tool is gdb, but printf is enough at the beginner stage. The demo's six sections each print a header line for exactly this reason: the output itself is the program's execution trace. Where the program got to and what it computed are visible at a glance.

Compilation actually happens in four stages, and it is worth seeing them once. Take a 3-line program as an experiment: gcc -E does preprocessing only, pasting in the header contents, and the result is 815 lines; gcc -S compiles to assembly, 45 lines; gcc -c assembles to an object file, a 1488-byte .o file; and the final link produces the executable. The 815 is the striking number: your 3 lines of code expand to 815 lines after preprocessing, most of them declarations pasted in from stdio.h. A header is not a "reference" — it is a literal text copy.

Once you see the four stages, many phenomena make sense. A preprocessing error cites a line inside a header file, because by then your code and the header are already mixed together; a compilation error points at your own source file; a link error most often reads "undefined reference," meaning some function was declared but its definition was never found — you called printf but forgot the standard library, or you wrote a function declaration and forgot its body. Reading errors by stage makes locating them twice as fast.

Functions are the next threshold. The demo keeps all its logic inside main; real projects do not: summing, sorting, and reading files should each be a function. A function's shape is fixed: return type, name, parameter list, and a body in braces. For example, int sum_to(int n) holds one for loop and returns sum. Call it as sum_to(100) and you get 5050. Extracting logic into a function has two benefits: main gets shorter and reads as "first sum, then sort, then print" instead of a pile of details, and when the same logic is needed again, you call the function instead of copying and pasting.

Variable scope follows the braces. An int i defined inside a for loop exists only inside that loop and is gone once the loop ends. A sum defined in main is visible throughout main. A variable defined inside a function disappears when the function returns. The rule looks simple, but it decides a variable's lifetime: stack variables are born with their braces and die with them, with no cleanup needed from you. Every variable in the demo works this way, which is why the beginner stage never touches malloc.

Memory comes in three regions, and the names are enough for now: the stack, the heap, and the global area. Local variables live on the stack, born with a function call and dead on return; memory from malloc lives on the heap and stays occupied until you free it; global and static variables live in the global area, present from program start until exit. The demo's three books and 8-number array all sit on the stack. The stack is small — typically 8 MB by default — and putting a multi-megabyte array on it crashes with a stack overflow; large blocks belong on the heap, requested with malloc. The difference between these three regions is the whole of C's memory model; the rest is detail.

Macros are another preprocessing tool. #define PI 3.14159 means: during preprocessing, every PI in the code is replaced verbatim with 3.14159. A macro has no type and no scope checking — it is pure text substitution. Defining constants with macros is convenient, but a sloppy macro bites: #define SQUARE(x) x*x called as SQUARE(1+2) expands to 1+2*1+2, which is 5, not 9. In modern C, use const where a constant will do and functions where logic will do. Knowing that a macro is text substitution is enough.

Learning C against Python speeds things up. Python's print maps to C's printf, except C's printf needs its own format specifiers; Python's list maps to C's array, except C's array has a fixed length and nobody stops an out-of-bounds index; Python's dict maps to C structs plus a pile of manual management; Python's exceptions map to C return-value checks — C has no exceptions, a function signals failure by returning a special value (fopen failing returns NULL), and the caller must check it. Everything Python does for you, C asks you to do yourself. The cost is verbosity; the return is complete control over what the program does.

One question every beginner asks: do you have to memorize the standard library? No — but know where to look it up. cppreference is the most-used C reference: the prototype, parameters, return value, and caveats of printf, fopen, and malloc are all there, one lookup at a time. When writing C, keeping cppreference open in the browser beats memorizing a manual. The GCC official documentation is the other bookmark worth keeping: the full descriptions of -Wall, -O2, and -std=c17 live there.

A checklist of common mistakes will save a lot of time. First, a missing semicolon: every C statement ends with one, and when it is missing the compiler often reports the error on the next line — do not trust the reported line number blindly. Second, a wrong main return type: main should return int, and return 0 means a normal exit. Third, a printf format specifier that does not match the variable type: %d for int, %ld for long, %zu for size_t, %f for double. A mismatched specifier prints a wrong number, and the compiler only warns — it does not error.

Fourth, array indices start at 0: for 8 numbers, the last one is a[7], not a[8]. Fifth, integer division drops the remainder: if you want decimals, at least one side must be floating-point. Sixth, == and = get mixed up: if (x == 1) compares, if (x = 1) assigns, and the second is always true. Seventh, forgetting fclose: unwritten file data may still sit in the buffer when the program exits, leaving the file empty.

When you finish this guide, you should be able to do four things: write a C program that compiles and runs, state how many bytes char, int, long, and double take on this machine, solve a small problem with loops and arrays, and build a three-book mini-project with structs and file I/O. Three directions open up next: pointers and dynamic memory (malloc and free), multi-file projects (headers and separate compilation), and a tour of the standard library (strings, math, time). None of them is urgent — type out the programs in this guide by hand first, get them running, and then move on.

Finally, a self-test list. First, write hello.c from memory, without looking at this article, and compile and run it. Second, recite the sizes of sizeof(char), sizeof(int), and sizeof(void*) on this machine: 1, 4, 8. Third, compute the sum of 1 to 100, 5050, and 10 factorial, 3628800, without a calculator. Fourth, change the demo's three books to three of your own, change the page counts, rebuild, run it, and confirm the total and the average change with them. Fifth, deliberately write the array index as a[8], compile with -Wall -Wextra, and see whether the compiler warns you — the answer is no, which is exactly why indices have to be counted by hand.

Sorting the demo array: before 7, 3, 9, 1, 8, 2, 6, 4; after 1, 2, 3, 4, 6, 7, 8, 9
Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles