Foundations of ComputingVol. 1 · Part I
0 / 0

Shelves / Foundations of Computing

CS·01

Start Here: Computers, Programs and Your Toolbox

The chapter to read first if you've never studied computer science, and a quick refresher if you have. What a computer is and what its parts do; what bits and bytes are; what a program and a programming language are; how to use a terminal (files, folders, paths, commands, input, output and exit codes); how to install the seven languages this book uses; writing, running and understanding your first program in C, C++, Java, Go, Rust, Zig and Python; a second program that reads input and handles bad data; how to read error messages; how to study with this book; and the vocabulary every later chapter assumes.

21 topics · ~26 min read · 17-question quiz
Updated Suggest a correction

How to read this book

This volume teaches the foundations of computer science, the ideas every other part of software engineering is built on. It's written for two kinds of reader at once, and you can use it either way.

If you're new to all of this

Read in order, starting with this chapter. Every chapter begins with a Start here section that explains its ideas in plain language, with everyday comparisons and small worked examples, before the full-depth sections. Inside the deeper sections:

  • Read a topic, then close the page and explain it aloud in your own words. If you can't, re-read; that's normal and it's how learning works.
  • Type the code yourself rather than copying it. Your fingers learn syntax, and the mistakes you make are the best teachers.
  • Answer the Check yourself questions before opening their answers.
  • Tick a topic's Done box only when you can explain it without looking.
  • Take the chapter quiz at the end. 80% or more counts as passed. A wrong answer shows an explanation: go back to that topic.

You won't understand everything on the first pass, and you don't need to. The deeper sections and the Lab at the end of each chapter are there for your second and third passes, weeks later. Each chapter's mastery ladder (L1 to L6) tells you how far you've got.

If you already work as a programmer

Use each chapter's Start here section as a fast check: if every idea in it is familiar and you can answer its Check yourself questions, skip to the full-depth sections, then the Lab, which is written for experienced readers: experiments that show the internals and the production consequences. The Revision sheet at the end of each chapter is a one-page summary for spaced review. The quizzes are mixed: the first questions in each chapter check basics, later ones probe depth.

new to the topic Start here full-depth sections quiz lab (second pass) already experienced check yourself depth + lab revision sheet quiz same chapters, different entry points
Two paths through each chapter. A newcomer reads the Start here section, then the full-depth sections, checks understanding with the quiz, and returns to the lab later. An experienced reader checks the Start here questions, goes straight to depth and the lab, and uses the revision sheet for spaced review. Both paths end at the same quiz.

What a computer is

Input, processing, storage, output

Strip away the screens and the brand names and every computer, from a phone to a data-centre server, does four things:

  1. Input: it receives data. Key presses, touches, a camera image, a file, a message from the network.
  2. Processing: it transforms data by following instructions. Adding numbers, comparing words, resizing a photo.
  3. Storage: it keeps data, briefly (while working) or permanently (files).
  4. Output: it produces results. Text on a screen, a saved file, a message sent over the network, a sound.

A calculator does all four in a tiny way: you type 7 × 6 (input), it multiplies (processing), keeps the numbers while working (storage), and shows 42 (output). What makes a computer different from a calculator is that the instructions themselves are data: you can load new instructions (a program) and the same machine becomes a word processor, a game or a web server.

The parts, and a kitchen to remember them by

operating system: the kitchen manager (who runs, who gets what) CPU (processor)the cook memory (RAM)the worktop: fast, small storage (SSD / disk)the pantry: big, slower input deviceskeyboard, network, camera output devicesscreen, network, speaker
The main parts of a computer, with a kitchen comparison. The processor is the cook who follows the recipe; memory is the worktop where ingredients currently in use are laid out; storage is the pantry that keeps everything, slower to reach; input and output devices are the doors where ingredients arrive and dishes leave. The operating system is the kitchen manager deciding whose order is cooked next.
  • The CPU (central processing unit, the processor) executes instructions: arithmetic, comparisons, moving data, deciding what to do next. It does billions of simple steps per second. Like a cook, it can only work on what's within reach.
  • Memory (RAM, random-access memory) holds the program that's running and the data it's working on right now. It's fast (the CPU can reach any part of it in about a ten-millionth of a second) but it's limited (8–64 GB in a typical laptop) and it forgets everything when the power goes off.
  • Storage (an SSD or hard disk) keeps files permanently: programs, documents, photos. It's much bigger and cheaper than memory, and also much slower to reach, so programs load data from storage into memory before working on it.
  • Input and output devices (I/O) connect the computer to the world: keyboard, mouse, screen, network card, camera, speakers.
  • The operating system (Windows, macOS, Linux, Android, iOS) is a program that manages all of this: it decides which program runs when, gives each program its own memory, and lets programs use files and devices without knowing the hardware details. Chapter 8 is about operating systems.

Chapter 7 explains the hardware properly; for now, the kitchen is enough.

Bits and bytes

Inside a computer, everything is stored as bits. A bit is a single yes-or-no value, written 0 or 1. Electronically it's a voltage that's either low or high, or a tiny region magnetised one way or the other. One bit can't say much, so bits are grouped:

  • 8 bits make a byte. A byte can hold 2⁸ = 256 different patterns (from 00000000 to 11111111), enough for one letter of English text or a number from 0 to 255.
  • Bigger units count bytes: a kilobyte (KB) is about a thousand bytes, a megabyte (MB) about a million, a gigabyte (GB) about a billion, a terabyte (TB) about a trillion. (Strictly, 1 KiB = 1,024 bytes, because computers count in powers of two; chapter 6 explains the KB/KiB difference.)

How can everything be bits? Because everything can be turned into numbers, and numbers can be written in binary (chapter 6 shows exactly how):

  • Text: each character gets a number. In the standard code used everywhere, A is 65, B is 66, a is 97, the space is 32. The word Hi is stored as the numbers 72 and 105.
  • Images: a picture is a grid of dots (pixels); each pixel's colour is three numbers (how much red, green and blue).
  • Sound: a sequence of numbers measuring air pressure many thousands of times per second.
  • Programs: each instruction for the CPU is a pattern of bits too.

The same bits mean different things depending on how they're interpreted: the byte 01000001 is the number 65 or the letter A. Keeping track of what bits mean is what types are for (chapter 2).

What a program is

A recipe for a very literal cook

A program is a list of instructions precise enough for a machine to follow without any judgement. That precision is the whole difficulty of programming: people fill gaps with common sense; computers don't.

Ask a friend to "make tea" and they'll manage. A computer needs every step: fill the kettle (how much? from which tap?), switch it on, wait until it boils (how do you know it has?), put a tea bag in a cup (which cup? which tea bag?)… and what to do when something goes wrong (no milk left?). Writing a program means thinking about all of that, including the unusual cases, which is where most bugs live.

Some vocabulary you'll meet constantly:

  • An algorithm is a step-by-step method for solving a problem, independent of any language. "To find the largest number in a list: remember the first one; look at each of the others; whenever one is bigger than what you remember, remember it instead; at the end, report what you remember." Chapter 4 is about algorithms.
  • A program is an algorithm (usually many) written in a programming language so that a computer can run it.
  • Source code is the program text that people write and read.
  • Running (or executing) a program means the computer actually follows its instructions.
  • A bug is a mistake that makes a program do the wrong thing; debugging is finding and fixing it.

Programming languages, and why there are so many

The CPU only understands machine code: numbered instructions in binary, specific to its type of processor. Nobody wants to write that, so we write in programming languages designed for people, and use translator programs to turn that into something the machine can run. There are two broad ways to translate (chapter 10 explains both in depth):

  • A compiler translates the whole program into machine code before it runs, producing a file you can execute directly. C, C++, Go, Rust and Zig work this way. It's like translating a whole book before anyone reads it.
  • An interpreter reads the program and carries out its instructions as it goes. Python works this way (with a twist: it first converts the code to a compact intermediate form). It's like a live interpreter at a meeting.
  • Java does both: a compiler turns source code into bytecode for a virtual machine (the JVM), which interprets it and compiles the busiest parts into machine code while the program runs.

Languages differ because they make different trade-offs between speed, safety, simplicity and expressiveness. This book uses seven so that you see what is universal and what is one language's choice:

Language Created Known for You'll see it used for
C 1972 Small, fast, close to the hardware; you manage memory yourself Operating systems, embedded devices, databases, the core of other languages
C++ 1985 C plus powerful abstractions (classes, templates) at no hidden cost Games, browsers, trading systems, high-performance libraries
Java 1995 Runs anywhere a JVM exists; automatic memory management; huge ecosystem Business backends, Android, big-data tools
Go 2009 Simple, fast to compile, built-in concurrency Cloud infrastructure (Docker, Kubernetes), network services
Rust 2015 C-like speed with memory safety checked by the compiler Systems software, browsers, infrastructure, tools
Zig 2016 A simpler, explicit modern alternative to C Systems programming, toolchains
Python 1991 Readable, quick to write, vast libraries Scripts, data science, AI, teaching, glue code

You don't need to learn all seven at once. If you're new, pick one to write in (Python or Go are gentle starts; Java if you're heading towards backend jobs; C if you want to see the machine) and read the others for comparison. The ideas transfer; the syntax is the easy part.

The terminal: talking to the computer in text

Why programmers use a terminal

Most people use computers through windows and icons. Programmers also use a terminal: a window where you type commands and the computer replies in text. The program that reads your commands is called a shell (Bash and Zsh on Linux and macOS; PowerShell on Windows). It's worth learning because compilers and developer tools are command-line programs, because typed commands can be repeated, scripted and shared, and because servers usually have no graphical interface at all.

On Linux, open "Terminal". On macOS, open Terminal (Applications → Utilities). On Windows, the smoothest route for this book is WSL (Windows Subsystem for Linux): install it with wsl --install in PowerShell, restart, and open "Ubuntu" from the Start menu. You then have a real Linux terminal, and every command in this book works as shown.

Files, folders and paths

Storage is organised as a tree of folders (also called directories) containing files and other folders. A path names a location in the tree:

/ home usr tmp asha projects notes.txt hello hello.py absolute path (from the root): /home/asha/projects/hello/hello.py relative path (from /home/asha): projects/hello/hello.py .. = the parent folder . = the current folder ~ = your home folder
A filesystem is a tree. The root directory "/" contains home, which contains asha, which contains projects and its hello folder with hello.py. An absolute path starts from the root (/home/asha/projects/hello/hello.py); a relative path starts from wherever you currently are (from /home/asha it is projects/hello/hello.py). Two dots mean the parent folder.
  • An absolute path starts at the top of the tree, the root, written / on Linux and macOS (Windows uses drive letters and backslashes: C:\Users\asha).
  • A relative path starts from the current directory, the folder your shell is "in" right now.
  • .. means "the parent folder", . means "this folder", and ~ means your home folder.
  • File extensions (.py, .c, .java) are a naming convention that tells people and tools what a file contains.

Your first commands

A short session, with the real output. Lines starting with $ are what you type (don't type the $); the other lines are the computer's replies.

Terminal
$ pwd                                  # print working directory: where am I?
/home/asha
$ mkdir -p projects/hello              # make the folder (and its parent, -p)
$ cd projects/hello                    # change directory: move into it
$ pwd
/home/asha/projects/hello
$ echo 'print("Hello from a file")' > hello.py     # write one line of text into a new file
$ ls -l                                # list files, long format
total 4
-rw-r--r-- 1 asha asha 27 Oct 29 07:31 hello.py
$ cat hello.py                         # show a file's contents
print("Hello from a file")
$ python3 hello.py                     # run it with the Python interpreter
Hello from a file
$ python3 hello.py > output.txt        # same, but send the output into a file instead of the screen
$ cat output.txt
Hello from a file
$ python3 missing.py
python3: can't open file '/home/asha/projects/hello/missing.py': [Errno 2] No such file or directory
$ echo $?                              # the exit code of the last command
2
$ cd ../..                             # up two levels
$ ls projects
hello
Command Meaning Example
pwd Show the current directory pwd
ls List files (-l long form, -a include hidden files) ls -la
cd Change directory (cd .. up one, cd ~ home, cd - back) cd projects
mkdir Make a directory (-p also creates parents) mkdir -p a/b/c
cat Print a file cat notes.txt
echo Print text echo hello
cp, mv Copy, move or rename mv old.txt new.txt
rm Remove a file (no recycle bin: it's gone; -r removes folders, carefully) rm output.txt
man, --help Read the manual for a command man ls, ls --help

Three ideas from that session that every later chapter uses:

  • Standard input and output. Every program starts with three channels: standard input (stdin: where it reads from, the keyboard by default), standard output (stdout: where normal results go, the screen by default) and standard error (stderr: where error messages go, also the screen). The shell can redirect them: > file sends stdout into a file, < file feeds a file into stdin, and | (a pipe) connects one program's output to the next program's input: cat notes.txt | sort.
  • Exit codes. When a program ends, it returns a number to the shell: 0 means success, anything else means some kind of failure (Python returned 2 for "file not found"). echo $? shows the last one. Scripts and build tools use exit codes to decide whether to continue.
  • Arguments. Words after a command's name are passed to the program: in python3 hello.py, the program is python3 and its argument is hello.py.

Setting up your toolbox

Installing the languages

Commands for Ubuntu or WSL (other systems: the language websites have installers; versions newer than those listed are fine):

Terminal
$ sudo apt update
$ sudo apt install -y build-essential           # gcc and g++ (C and C++) and make
$ sudo apt install -y openjdk-21-jdk            # Java 21 (long-term support release)
$ sudo apt install -y python3 python3-pip       # Python 3
$ sudo apt install -y golang-go                 # Go (or the newer release from go.dev/dl)
$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh    # Rust, via its official installer
$ pip install ziglang                           # Zig, as a Python package: run with  python3 -m ziglang
$ gcc --version; java -version; python3 --version; go version; rustc --version; python3 -m ziglang version

sudo runs a command with administrator rights (it asks for your password); apt is Ubuntu's package manager, a program that downloads and installs software. You also need a text editor for code: Visual Studio Code is the common free choice (on Windows with WSL, install its WSL extension so it edits files inside Ubuntu). Anything that saves plain text works; word processors like Word don't (they add formatting).

The edit, build, run loop

Whatever the language, you'll repeat one loop thousands of times:

edit source build run check result compile error crash or wrong answer next feature
The programming loop. Write or change the source code in an editor, build it (compile, for compiled languages), run it, look at what happened, and go back to the editor. Errors can stop you at the build step (the compiler found a problem) or at the run step (the program misbehaved), and each sends you back to edit.

Your first program, in seven languages

Hello, world

By tradition (since a 1978 book on C), the first program prints "Hello, world!". It's tiny, but it proves the whole toolbox works: editor, compiler or interpreter, terminal. Here it is in all seven languages, each compiled and run for this book:

#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}

How to run each, from the folder containing the file:

Terminal
$ gcc hello.c -o hello_c && ./hello_c            # C: compile to an executable, then run it
Hello, world!
$ g++ hello.cpp -o hello_cpp && ./hello_cpp      # C++
Hello, world!
$ javac Hello.java && java Hello                 # Java: compile to Hello.class, run on the JVM
Hello, world!
$ java Hello.java                                # Java 11+: compile and run in one step (single files)
Hello, world!
$ go mod init hello && go run .                  # Go: create a module once, then build and run
Hello, world!
$ rustc hello.rs -o hello_rs && ./hello_rs       # Rust (bigger projects use: cargo new / cargo run)
Hello, world!
$ python3 -m ziglang run hello.zig               # Zig: build and run
Hello, world!
$ python3 hello.py                               # Python: the interpreter runs the source directly
Hello, world!

(&& means "run the second command only if the first succeeded", using the exit code. ./hello_c means "the program hello_c in the current folder".)

Reading it line by line

Take the C version, since it shows the most:

  • #include <stdio.h> asks for the declarations of the standard input/output library, where printf lives. Every language has a way to use code from libraries: import in Java, Go and Python, use in Rust, @import in Zig.
  • int main(void) { … } defines a function named main. A function is a named block of instructions. main is special: it's where the program starts. (Python has no main requirement: it runs the file from top to bottom.)
  • printf("Hello, world!\n"); calls the function printf with one argument, the text "Hello, world!\n". Text in quotes is a string; \n is the newline character, which moves to the next line. The ; ends the statement.
  • return 0; ends main and hands back the exit code 0: success.
  • { and } group statements into a block. Indentation is for human readers in C, Java, Go and Rust; in Python, indentation is the grouping, so it must be consistent.

Notice what is the same across all seven: a starting point, a call to a printing function, a string. Notice what differs: how libraries are named, whether there's a class (Java requires one), how strict the boilerplate is. Chapter 2 explains each piece properly.

A second program: input, decisions and repetition

Averaging numbers safely

A real program reads input, makes decisions and repeats work. This one reads numbers, one per line, until the input ends, then reports how many there were, their total and their average. It also handles a line that isn't a number (it skips it with a message) and the case of no numbers at all (it doesn't divide by zero).

# Read numbers (one per line) until the input ends, then print how many, the total and the average.
count = 0
total = 0.0
while True:
    try:
        line = input()
    except EOFError:            # no more input
        break
    line = line.strip()
    if line == "":
        continue                 # skip blank lines
    try:
        value = float(line)
    except ValueError:
        print(f"skipping {line!r}: not a number")
        continue
    count = count + 1
    total = total + value
if count == 0:
    print("no numbers")
else:
    print(f"count={count} total={total:.2f} average={total / count:.2f}")

Running it with a file of input (120, 80, lunch, an empty line, 150.5), every version prints the same result:

Terminal
$ printf '120\n80\nlunch\n\n150.5\n' > in.txt
$ python3 avg.py < in.txt
skipping 'lunch': not a number
count=3 total=350.50 average=116.83

(You can also run it and type numbers yourself; press Ctrl+D on Linux/macOS, or Ctrl+Z then Enter on Windows, to signal "end of input".)

This little program contains most of the building blocks of all programs, each of which chapter 2 explores:

  • Variables (count, total): named places that hold values that change as the program runs.
  • Types: count is a whole number (integer), total a number with a fractional part (floating point), line text (a string).
  • A loop (while, for): repeat until the input ends.
  • Decisions (if/else): skip blank lines; avoid dividing by zero.
  • Conversion from text to number, and error handling when conversion fails (try/except in Python, try/catch in Java, an err value in Go, match on Ok/Err in Rust, checking end == line in C).
  • Input and output: reading lines from standard input, printing formatted results.

Tracing a program by hand

The most important beginner skill is predicting what a program will do before running it. Do it with a trace table: one column per variable, one row per step. For the input above:

Line read Is it a number? count after total after
(start) 0 0.0
120 yes 1 120.0
80 yes 2 200.0
lunch no: print "skipping" 2 200.0
(empty) skipped 2 200.0
150.5 yes 3 350.5
(end of input) 3 350.5

Average = 350.5 / 3 = 116.83. If your table and the program's output disagree, either your understanding or the program is wrong, and finding out which is debugging.

When things go wrong: reading error messages

Three kinds of errors

Error messages look frightening at first, but they're the computer telling you exactly what it noticed and where. Learn to read them calmly, top to bottom. There are three kinds:

  1. Compile-time errors (in compiled languages): the compiler refuses to build the program. Your mistake is in the text: a typo, a missing symbol, mismatched types.
  2. Run-time errors: the program starts but crashes, or stops with an error, when it reaches a bad step (dividing by zero, using something that doesn't exist).
  3. Logic errors: the program runs and finishes but gives the wrong answer. No message at all: only testing finds these, which is why chapter 2 covers testing.

Four real messages, decoded

A C program with a missing semicolon and a misspelt variable:

C
int main(void) {
    int total = 10
    printf("%d\n", totl);
    return 0;
}
Terminal
$ gcc err.c
err.c: In function 'main':
err.c:5:5: error: expected ',' or ';' before 'printf'
    5 |     printf("%d\n", totl);
      |     ^~~~~~

Read it as: file err.c, line 5, column 5: the compiler expected , or ; before printf. The mistake is actually at the end of line 4 (the missing ;), but the compiler only noticed when it reached line 5. Look at the reported line and the line before it. Fix that, and the compiler will then report the next problem (totl undeclared). Always fix the first error first: later ones are often consequences of it.

A Python program with a misspelt name:

Python
prices = [120, 80, 150]
total = 0
for p in prices:
    total = total + p
print("Average:", total / len(price))
Terminal
$ python3 err.py
Traceback (most recent call last):
  File "/tmp/C01/err.py", line 5, in <module>
    print("Average:", total / len(price))
                                  ^^^^^
NameError: name 'price' is not defined. Did you mean: 'prices'?

A Python traceback lists where the error happened; the last line is the most important: the error type (NameError) and the message, here with a helpful suggestion. Because Python is interpreted, this error appeared only when line 5 ran: the loop before it worked fine.

A Go program giving a variable the wrong type:

Go
var count int = "three"
Terminal
$ go build .
./main.go:6:18: cannot use "three" (untyped string constant) as int value in variable declaration

count was declared to hold integers, and "three" is text. Go (like C, C++, Java, Rust and Zig) checks types before running, so this mistake can never reach users.

A Java program reading past the end of a list:

Java
int[] scores = {90, 75, 60};
System.out.println(scores[3]);
Terminal
$ java Err
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at Err.main(Err.java:4)

This compiled fine (the compiler can't always know which positions exist) and failed at run time. The three scores are at positions 0, 1 and 2: counting from zero is the convention in almost every language, and "off by one" is the most common beginner bug. The stack trace line at Err.main(Err.java:4) points to the exact line.

How to learn this material

Methods that work

Decades of research on learning agree on a few methods, and this book is built around them (Volume 17, chapter 194A, has the details):

  • Active recall: test yourself instead of re-reading. Close the book and write down what you remember; answer quiz questions; explain aloud. Re-reading feels productive but builds far less memory than retrieval.
  • Spaced repetition: review after a day, a week, a month. Retake chapter quizzes on that schedule; use the revision sheets.
  • Doing, not watching: type every example, change it, break it on purpose and fix it.
  • Interleaving: mix topics and languages once the basics are in place; seeing the same idea in C and in Python makes the idea, not the syntax, stick.
  • Small daily practice beats occasional marathons: 30–45 focused minutes most days moves you further than one exhausted weekend.

The mastery levels

Each chapter has a ladder from L1 to L6. For a first pass, aim for L2 (you can use the idea correctly) and L3 (you can explain why it works). The labs push towards L4 (you can diagnose problems). L5 and L6 come from building and running real systems, which is what the projects in chapter 11 and the later volumes are for.

Level You can… Example for "variables"
L1 Recognition Define it and spot it "A variable is a named place that holds a value"
L2 Working Use it correctly Write loops that update counters correctly
L3 Internals Explain why it works Explain where a local variable lives in memory and why it disappears when a function returns
L4 Debugging Diagnose problems Find why two variables unexpectedly change together (aliasing)
L5 Design Choose among approaches Decide between mutable and immutable data for a module
L6 Production Operate it at scale over time Prevent a class of shared-state bugs across a large codebase

Vocabulary for the rest of the book

A starter glossary

Term Meaning
Algorithm A step-by-step method for solving a problem
Argument A value passed into a function or program
Binary The base-2 number system, using only 0 and 1
Bit / byte One binary digit / a group of 8 bits
Bug / debugging A mistake in a program / finding and fixing it
Compiler A program that translates source code into an executable form before running
CPU The processor that executes instructions
Exit code The number a program returns when it ends; 0 means success
Function A named, reusable block of instructions that can take inputs and return a result
Interpreter A program that executes source code (or an intermediate form) step by step
Library Reusable code written by others that your program can use
Loop A construct that repeats instructions
Memory (RAM) Fast, temporary storage for running programs and their data
Operating system The program that manages hardware and runs other programs
Path The name of a file's location in the folder tree
Shell / terminal The program that reads typed commands / the window you type them in
Source code The human-readable text of a program
Standard input / output / error The default channels a program reads from and writes to
Storage Permanent memory for files (SSD, disk)
String A piece of text
Type What kind of value something is (integer, text…), deciding what you can do with it
Variable A named place that holds a value