Foundations

Reading map

Reading map Next: Programming in Pascal

Volume I: Foundations of Programming (Chapter 1)Code & tests Chapter diagrams Download editable SVGs

Chapter Map

Computer: What Is It?

A computer was originally designed to perform calculations, but today it handles far more than arithmetic alone.

Detailed notes - 1.1: Computer: what it is

1

computer originally = a device for carrying out calculations

  • even a calculator application spends much of its work on the interface
  • history explains the change from arithmetic machines to general information processing

A Little Bit of History

Year Who / What Key Development
1645 Blaise Pascal Builds the oldest surviving mechanical calculator
1840s Charles Babbage Develops the idea of the programmable Analytical Engine
1840s Ada Lovelace Writes an early program idea
1938 Konrad Zuse Builds the Z1, an early programmable machine
1940s Vacuum-tube computers 1st generation: electronic computers based on vacuum tubes
1950s Transistors, core memory 2nd generation: smaller, more reliable transistor computers
1960s Integrated circuits 3rd generation: computers built from integrated circuits
1971 Microprocessors 4th generation: a whole CPU fits on a single chip
Detailed notes - 1.1.1: A little history

1

Schickard's calculating clock (1623): mechanical arithmetic

  • addition / subtraction of six-digit integers; bell signals overflow
  • original lost; working reconstruction made in 1960
  • Leonardo's earlier drawings do not establish that a machine was built

2

Pascal's calculator: work started in 1642; surviving machine from 1645

  • intended to help his father with tax calculations
  • decimal wheels; first five digits, later machines with more digits
  • addition directly; subtraction through complements

3

fixed five-digit arithmetic: carry beyond the last digit disappears

  • 00500 - 00134 = 00500 + 99866 -> 00366
  • replace x - y with x + (100000 - y); overflow supplies the final subtraction

4

100000 - y = 99999 - y + 1

  • replace every digit by its complement to 9, then add 1
  • 00134 -> 99865 -> 99866; no borrowing needed

5

Pascal's actual subtraction method:

  • display both ordinary digits and their complements to 9
  • enter complement of x, add y, read the complementary display
  • 99499 + 00134 = 99633 -> complementary reading 00366

6

complements are relevant beyond mechanical calculators

  • complement followed by adding 1 returns in machine representation of negative integers

7

Leibniz's machine: addition, subtraction, multiplication and division

  • multiplication through repeated additions; division through repeated subtractions
  • did not itself calculate square / cube roots, although multiplication helps with them

8

mechanical calculators lasted into the twentieth century

  • each individual operation automated
  • human still chose operations, recorded intermediate results and entered them again

9

Babbage's difference engine: proposed in 1822; work began in 1823

  • finite differences -> automatic tables of polynomial approximations
  • expensive project remained unfinished
  • Babbage turned toward a universal machine instead of one special calculation

10

Scheutz built a working difference engine in 1843

  • later sold machines to governments
  • modern reconstructions from Babbage's drawings demonstrated that the design could work

11

Babbage's analytical engine: proposed universal programmable machine

  • program controls operations
  • move intermediate results between storage locations
  • choose actions according to comparisons / analysis of data
  • design exceeded the practical engineering possibilities of its time

12

Ada Lovelace translated Menabrea's account of Babbage's lecture

  • added extensive notes, including instructions for Bernoulli numbers
  • commonly described as the first computer program
  • recognized possible manipulation of information beyond numbers, including music

13

book corrects a Russian quotation falsely attributed to Lovelace

  • author had reproduced it in earlier editions
  • checking the original revealed a much more specific discussion of music
  • -> repetition in many sources does not establish authenticity

14

origin of the false quotation is uncertain

  • circulated before easy access to original sources
  • book warns against treating this Russian wording as Lovelace's statement

15

Zuse's Z1 (1938): mechanically implemented binary programmable machine

  • motor supplied motion; shaped metal plates implemented logical operations
  • illustrates that binary logic does not require electronic components

16

Zuse's successive machines:

  • Z1 unreliable; Z2 used relays for computation and mechanical memory
  • Z1 / Z2 read punched tape without rewinding -> no program loops
  • Z3 used relays and allowed loops, but lacked conditional jumps
  • Z4 added branching; completed in 1944 and survived the war

17

Zuse's work remained little known outside Germany

  • wartime research also produced relay and vacuum-tube computers elsewhere

18

vacuum-tube diode:

  • heated cathode emits electrons; anode attracts them
  • vacuum contains no ions carrying a reverse current
  • -> current passes in only one direction

19

triode adds a control grid between cathode and anode

  • negative grid potential obstructs electrons
  • a small varying signal controls a larger current -> amplification

20

two cross-coupled triodes form a flip-flop

  • one conducts and keeps the other closed
  • pulse changes their roles -> two stable states -> one stored bit
  • other connections implement AND, OR and NOT

21

vacuum tubes remove mechanical delays but have limited reliability

  • ENIAC contained about 18000 tubes
  • failure of one component could require repair before computation continued

22

book's account of ENIAC / Colossus:

  • Mauchly and Eckert's ENIAC project became public after the war
  • secrecy and destruction of Colossus equipment / documentation delayed recognition of Flowers's work

23

book discusses conflicting accounts linking wartime secrecy to Coventry

  • treats the proposed explanation for destroying equipment as disputed

24

Colossus and Bombe are different machines

  • Colossus: Flowers's electronic work against Lorenz ciphers
  • Bombe: electromechanical machine associated with Turing and Enigma
  • book rejects attributing the Colossus project directly to Turing

25

Turing had worked with Flowers and recommended him for the Lorenz project

26

first computer generation = electronic computers using vacuum tubes

  • mechanical / relay machines fall outside this classification

27

stored-program principle:

  • instructions and data occupy the same uniform memory
  • instruction codes are representable as ordinary data
  • -> associated with the name von Neumann architecture

28

EDVAC report and attribution:

  • Mauchly, Eckert, von Neumann and others discussed the design
  • von Neumann wrote the draft; circulated copies carried his name
  • book stresses collective origins of the architectural ideas

29

IAS was built under von Neumann's direction

  • not the first stored-program machine
  • book discusses Manchester Baby, EDVAC and MESM as earlier implementations

30

Feynman's account of fascination with computing:

  • experimenting with what a machine can do can distract from assigned work
  • author sees this curiosity as an important motivation for becoming a programmer

31

before stored programs, preparing a computation could require days of rewiring

  • ENIAC program embodied connections / switch settings
  • machine spent substantial time being configured between short calculations

32

stored instructions change both preparation and possibilities:

  • prepare a program separately, then load it quickly
  • process programs as data -> compilers and operating systems become possible

33

von Neumann architecture includes further principles beyond storing programs

  • fuller treatment appears in 3.1.1

34

early memory was very small

  • ENIAC initially used twenty ten-digit accumulator registers
  • Manchester Baby: 32 words of 32 bits
  • IAS word: one 40-bit number or two 20-bit instructions

35

LEO I: business information processing at J. Lyons & Co.

  • payroll, accounting and financial analysis
  • punched-tape input and printed documents
  • arithmetic only one part of the overall information processing

36

transistor provides electronic control analogous to a triode

  • small input controls current through another path
  • useful both for amplification and switching
  • two suitably connected transistors can store a bit

37

book traces the transistor to Bell Labs work in 1947

  • improving manufacture made components smaller and more reliable
  • no heated cathode -> much lower power consumption than tubes

38

magnetic-core memory: ferrite rings store individual bits

  • transistor circuits + improved memory -> second computer generation
  • smaller size, lower cost / power, larger memory and better reliability

39

integrated circuits place many components on one crystal

  • third generation: computers assembled from integrated circuits
  • increasing integration eventually puts a whole CPU on one chip
  • Intel 4004 is identified as the first commercially available microprocessor
  • book also discusses the competing historical claim concerning MP944

40

microprocessor -> affordable desktop / personal computer

  • book calls this the fourth generation
  • treats the Japanese fifth-generation project as a different software direction

41

computers process any information with a usable representation

  • texts, databases, sound, images and video
  • book discusses tactile devices and limitations of recording taste / smell

42

computation is broader than arithmetic

  • supercomputers still serve large numerical tasks
  • a mathematical function may map objects of arbitrary kinds
  • digital information becomes strings over an alphabet
  • -> information processing = computing a function from strings to strings

Processor, Memory, Bus

Component Role
CPU Execute instructions using registers
RAM Addressable working memory; volatile
ROM / firmware Retain startup code across power loss
Bus Carry addresses, data, and read/write signals
Controller / driver Hardware interface / software that controls it
OS Protect and allocate memory; manage tasks, devices, and files
Detailed notes - 1.1.2: CPU, RAM, bus

1

bus: parallel lines carrying signals between components

  • address bus: which location / controller responds
  • data bus: transferred information
  • control bus: operation to perform

connected to CPU, RAM and external-device controllers

  • RAM / controllers respond only when their address is selected

2-3

RAM: uniform addressable memory locations

  • each location has its own address
  • N address lines -> 2^N possible addresses
  • these addresses form the physical address space

virtual address space: addresses presented to a program; introduced later

4-5

memory access: read or write

  • CPU selects address and sends operation signal
  • read: selected location places its value on data bus
  • write: selected location takes new value from data bus; old value lost
  • several adjacent locations can hold one value

RAM is volatile: contents disappear when power is removed

6

RAM != disk storage

  • CPU accesses RAM directly
  • disks require controller operations performed by driver programs

7-8

ROM: retains contents without power; ordinary CPU writes cannot change it

  • startup program checks hardware, finds and loads the OS

OS is a program:

  • receives privileged access and controls later programs
  • user programs work in allocated memory and request other actions from OS
  • drivers organize work with external devices

9

files: OS organization of information in long-term storage

  • names allow users to find saved information

RAM allocation changes with running programs

  • OS tracks assigned regions
  • each program accesses its own allocated memory
  • memory regions do not need user-facing file names

Clarification. Files are a filesystem abstraction: they can also live in RAM or represent generated data. The disk-only wording in these introductory notes describes persistent disk files.

select address -> signal read/write -> transfer data between registers and RAM
Read and write transactions select the same addressed byte but reverse the data direction.
One address, one selected memory location. Open full size - Editable SVG

Principles of Operation of the Central Processor

Detailed notes - 1.1.3: CPU principles

1

CPU executes primitive operations specified by a program

  • registers hold information being processed
  • memory read / write transfers information between RAM and CPU

2

instruction set: operations implemented by a particular CPU

  • arithmetic, register copying, logical operations and jumps
  • some CPUs also operate directly on memory operands

3

machine instruction has an operation code

  • program = machine instructions stored in RAM

instruction pointer stores address of next instruction

CPU execution cycle:

  • fetch instruction at that address
  • advance instruction pointer by instruction size
  • decode and execute instruction
  • repeat

4

jump instructions explicitly change the instruction pointer

  • conditional: transfer only if condition holds
  • unconditional: transfer without a test
  • subroutine call: transfer while remembering return point
instruction pointer -> fetch -> advance pointer -> decode / execute -> repeat
Fetch advances the instruction pointer; a taken jump replaces its value.
The instruction pointer controls the next step. Open full size - Editable SVG

External Devices

Detailed notes - 1.1.4: External devices

1

computer needs devices for input, output and long-term storage

  • direct CPU connections become inconvenient as device types multiply
  • -> common bus and controllers separate CPU from device details

2

controller connects its device to the bus

  • CPU communicates through read / write operations
  • controller addresses may share memory address space or occupy I/O space
  • one controller can expose several I/O ports

port write: issue command / data

port read: obtain device status / results

3

driver knows the particular controller's ports and command meanings

  • normally part of the OS

file-write example:

  • application requests OS to write a file
  • OS determines disk location
  • disk driver issues controller commands
  • controller performs operation
  • driver checks status and reports result to OS

Clarification. The prevalence of port I/O versus memory-mapped I/O depends on the architecture. Both kinds of access can have side effects.

software: program -> OS -> driver
hardware: CPU <-> bus <-> controller <-> device

Hierarchy of Storage Devices

Detailed notes - 1.1.5: Storage hierarchy

1

storage choices balance access speed, capacity and retention time registers: fastest access; small fixed capacity determined by CPU design

  • adding registers increases CPU complexity and cost

2

cache contains copies of information from RAM

  • keeps frequently needed data close to CPU
  • avoids slower communication with main memory
  • faster access requires more complex / expensive hardware

3

cache may have several levels

  • farther levels generally trade speed for capacity
  • book's particular level count / chip arrangement describes its hardware context

4

RAM holds executing programs and their working data

  • larger capacity than registers / cache, but still finite
  • RAM, cache and registers lose contents without power

5

disks / flash storage: persistent storage with access to arbitrary blocks

  • larger capacity and lower cost per unit than RAM
  • slower I/O through controllers
  • program code and working data must be loaded into RAM for CPU use
  • files normally reside here

6

magnetic tape: archival storage with sequential access

  • data normally copied to disk before use
  • drive expensive; many inexpensive cartridges reduce total cost per unit
  • appropriate storage conditions permit long retention
  • reading old media still requires compatible working equipment

Summary

The CPU executes instructions using registers and RAM. Buses connect it to memory and device controllers; the OS manages resources and drivers translate device operations.

Detailed notes - 1.1.6: Summary

1

CPU and RAM communicate through bus; external devices through controllers

  • drivers operate controllers
  • persistent files hold programs / data
  • load programs / data into RAM before processing

2

OS starts first and controls the machine

  • ordinary programs receive restricted access
  • operations beyond transforming assigned memory require OS services

3

these principles are prerequisites for programming

  • reread unclear material and resolve misunderstandings before proceeding

Using a Computer Properly

Unix treats the command line as a primary interface: commands are fast, composable, repeatable, and easy to automate.

Operating Systems, Interfaces, and Unix

Period Development
Late 1960s MULTICS influences Ken Thompson's early Unix work at Bell Labs
1970s Thompson and Dennis Ritchie develop Unix and the C language
1973 Most of Unix is rewritten in C, making portability practical
1977 onward Berkeley develops BSD and major Unix networking tools
1984 Richard Stallman starts the GNU free-software project
1991 Linus Torvalds publishes the first Linux kernel
Today Linux, BSD, macOS, Android, and commercial systems preserve Unix ideas

For daily work:

Detailed notes - 1.2.1: Operating systems and user interfaces

1

OS manages programs and peripheral devices

  • application requests a file by name and reads data into memory
  • OS handles device-specific work, including local / removable / network storage

2

book surveys Windows and the Unix family

  • Linux distributions, BSD systems, Android and Apple systems
  • describes relationships in the computing landscape of its edition

3

user interface can be an ordinary program outside the kernel

  • Unix separates interface programs from core OS responsibilities
  • book contrasts this with tighter Windows integration

4

many servers do not need a local graphical interface

  • machines run in equipment rooms; administrators manage them remotely
  • some have no video hardware at all

5

computer use does not inherently require graphics

  • text-mode file managers and even text-mode windows existed before widespread GUIs

6

widget interfaces arrange buttons, menus, input fields and other controls

command-line interface:

  • user enters commands; computer executes them and reports results
  • interactive dialogue differs from submitting batches of jobs

7

teleprinter: keyboard input travels through a communication line

  • received characters are printed on paper
  • originally used for remote written communication

8

connecting teleprinters to computers enabled interactive command entry

  • commercially available devices avoided designing a new terminal

9

alphanumeric screen terminals replace printed output with display output

  • keyboard still sends characters through a line
  • removes continual paper consumption

10

escape sequences control terminal display

  • move cursor, change attributes / colours, alter existing screen contents

11

terminal emulation reproduces terminal behaviour in software

  • serial connection can configure a server before network access exists
  • later administration normally uses the network

12

command interpreter / shell:

  • displays prompt, reads a command line, executes it
  • first word identifies command; following words are arguments
  • built-in commands handled by shell; others found as executable files
  • one line can combine several cooperating commands

13

Unix does not force users to avoid a GUI

  • book uses macOS as an example of Unix foundations with a graphical environment
  • professionals can also choose its terminal / shell

14

window manager controls window appearance and behaviour

  • Unix users can choose different managers independently of applications

15

Unix offers icon-based and two-panel file managers

  • author prefers shell commands for frequent file operations

16

book contrasts Unix shells with the Windows command interpreter of its period

  • notes availability of Unix-derived tools on Windows

17

both graphical and command interfaces require learning

  • familiar GUI gestures can conceal how much was learned
  • author argues that habit with one interface is not universal intuitiveness

18

command editing, history and filename completion reduce typing

photo-copy example:

  • enter destination year directory; create trip directory
  • mount card; copy photos; unmount card
  • Tab completes paths; history recalls commands / previous arguments

19

repeated command sequence can become a shell script

  • trip directory supplied as argument: ./getphotos Milan
  • improved version checks missing argument and reuses a destination variable
  • -> explicit commands allow the procedure to be parameterized and repeated

20

graphical applications can also start from a shell

  • program name followed by document / URL and other arguments
  • trailing & permits continued shell use

21

shell composition:

  • insert command output into another command
  • pipe one program's output into another program's input
  • combine existing tools in ways their authors did not anticipate

22

author treats command-line competence as essential professional preparation

  • also uses it as a teaching tool throughout the book

23

book assumes a Unix system and regular command-line work

  • remaining chapter introduces the required everyday skills
Detailed notes - 1.2.2: History of Unix

1

Bell Labs participation in MULTICS preceded Unix

  • after leaving the project, Ken Thompson developed a smaller system on a PDP-7
  • book relates the development to his interest in games and available hardware

2

UNICS name proposed by Kernighan; spelling later became Unix

  • Thompson and Ritchie moved system to PDP-11
  • B was too limited for desired system implementation
  • Ritchie's extension of B became C

3

Unix rewritten in C in 1973

  • challenged the assumption that an OS must be written in low-level language
  • linked the later development of Unix and C

4

1974 paper attracted users, especially at universities

  • AT&T's legal position encouraged noncommercial source distribution
  • port to Interdata 8/32 completed in 1977
  • portable C compiler helped separate system implementation from one CPU

5

Berkeley contributed the BSD branch

  • BSD = Berkeley Software Distribution
  • research began in the 1970s; Bill Joy produced first distribution in 1977

6

AT&T commercialization brought licensing disputes

  • Berkeley worked to remove AT&T-owned code
  • book describes eventual settlement after Unix business passed to Novell

7

legal uncertainty delayed freely available Unix on inexpensive Intel machines

  • 80386 had suitable hardware capabilities before widespread free ports appeared

8

Stallman's free-software movement developed tools for a free system

  • lacked a complete free kernel
  • Torvalds began an independent Unix-like kernel for i386 in 1991

9

Torvalds's initial terminal-emulator project expanded

  • scheduler handled incoming / outgoing streams
  • file-transfer needs led to disk support
  • -> growing set of components became an operating-system kernel

10

publishing intermediate source attracted volunteer developers

11

Linux name supplied by another participant; Torvalds had considered Freax

  • first public code in 1991; version 1.0 in 1994
  • BSD disputes helped Linux gain an early audience
  • kernel plus existing free tools provided a usable free system

12

Linux has many copyright holders

  • book explains distribution under GNU GPL v2
  • one company cannot simply purchase all contributors' rights as one owner's asset

13

Unix now denotes a broad family and shared approach

  • book distinguishes free Linux / BSD systems from commercial Unix variants

14

Unix foundations survived major changes in hardware and interfaces

  • graphical environments can be added without replacing core principles
  • Android uses Linux; Apple systems have BSD-related ancestry
Detailed notes - 1.2.3: Unix on a home computer

1

book introduces freely distributed Unix systems and their application packages

  • installation instructions and software available from their communities

2

author recommends a Linux distribution for the first installation

  • BSD variants can be explored after gaining experience

3

transition can be gradual; immediate abandonment of the previous environment unnecessary

4

separate spare computer is one possible installation target

  • lightweight systems can make older hardware useful
  • very old hardware may restrict available application versions

5

another option: allocate disk space alongside an existing OS

  • preserve needed files before repartitioning / replacing a filesystem
  • book's quoted capacity is an example from its period

6

author prefers a lightweight window manager

  • distinguishes window management from a complete desktop environment
  • this preference supports the book's emphasis on shell use

7

find and configure a terminal emulator

  • book suggests an 80-column layout and comfortably readable character size
  • background / text colour recommendations reflect the author's preference

8

make opening a terminal easy

  • keyboard shortcut or readily accessible launcher
  • save suitable font / window settings
  • -> comfortable setup reduces friction during study

9

install applications needed for ordinary work

  • browser, office documents, PDF / image viewing, audio / video
  • learn the equivalents of familiar tasks in the new environment

10

book's programming tools:

  • text editors: Vim, JOE, nano
  • Free Pascal, NASM, GCC with C / C++ support
  • make and GDB
  • package names can differ between systems

11

use an unprivileged account for ordinary work

  • administrative access reserved for system changes
  • book additionally expresses its own preference for separate root sessions over sudo
  • console-switch key examples depend on system configuration
Detailed notes - 1.2.4: First session in a computer classroom

1

classroom Unix may run locally or on a shared remote server

  • basic user workflow remains similar

2

log in with assigned username and password

  • letter case matters; Login incorrect can mean either value is wrong

3

obtain a shell

  • remote terminal / text console normally provides it after login
  • graphical session: open xterm or another terminal emulator
  • book uses startx for starting an X session where configured

4

change an initially assigned password using passwd

  • current password, then new password twice; characters are not echoed
  • book gives a mnemonic phrase method and period-specific composition advice
  • keep account credentials private; do not let others work under your identity

Files and Paths

Unix has one tree. / is its root, ~ is the home directory, . is the current directory, and .. is its parent.

Command Purpose
pwd Print the current directory
ls -aF List all entries and mark their types
cd dir Enter dir
cd Return to the home directory
cp src dst Copy a file
mv old new Move or rename a file
rm file Remove a file
mkdir dir Create a directory
rmdir dir Remove an empty directory
touch file Create a file or update its timestamp
less file View text page by page
/home/vasya/photos/mars.jpg  absolute path
photos/mars.jpg              relative path
../vasya/photos/mars.jpg     relative path through the parent
./program                    program in the current directory

Each process has its own current directory. Changing directory in one terminal does not change another terminal.

Detailed notes - 1.2.5: Directory tree and file operations

1

example prompt: user@host:directory$

  • prompt is printed by shell; do not type it as part of command
  • ~ represents home directory; # conventionally marks administrator prompt

2

Unix path conventions:

  • one directory tree; no drive letters
  • / separates directory components

3

login starts in home directory

  • pwd: print current directory
  • ls: list names; ls -a includes names beginning with .
  • ls -F marks types, including / for directories
  • . = current directory; .. = parent directory

4

cd changes current directory

  • cd tmp: child directory; cd ..: parent
  • cd /usr/include: specified absolute path; cd /: root
  • cd without argument: home directory

5

each process has its own current directory

  • changing directory in one shell does not change another shell's directory

6

basic file operations:

  • cp: copy; mv: move / rename; rm: remove
  • mkdir / rmdir: create / remove directory
  • touch: create empty file or update timestamps; less: view contents
  • options modify commands; rm -r removes a directory tree recursively

7

absolute path starts with / and is independent of current directory

  • /home/vasya/photos/mars.jpg identifies each component from root

8

short name refers to an entry in current directory

  • mars.jpg works when current directory is /home/vasya/photos

9

relative path starts from current directory

  • photos/mars.jpg from /home/vasya
  • ../vasya/photos/mars.jpg from /home/anya
  • each .. ascends one directory level

10

paths can include redundant descents / ascents

  • system resolves these components rather than requiring a shortest spelling
  • useful when a program constructs a path from separate pieces

11

. can appear inside a path

  • ./photos/./mars.jpg refers through the current directory at each . component

12

file path = name including directory components

  • commands generally accept absolute / relative paths wherever a filename is expected

13

book recommends simple portable filenames

  • letters, digits, . and _; - acceptable except as initial character
  • spaces / punctuation require quoting; leading - can be mistaken for an option
Absolute paths begin at root; relative paths start at the current working directory.
Two paths, one directory-tree destination. Open full size - Editable SVG

Commands, Quoting, and Patterns

A command line contains a command name followed by arguments. Semicolons separate commands.

ls -a ; pwd ; echo abrakadabra

mv Photos\ from\ Paris Photos_from_Paris
mv 'Photos from Paris' Photos_from_Paris
mv "Photos from Paris" Photos_from_Paris
Form Meaning
\x Treat the next character literally
'text' Treat every character as literal text
"text" Preserve spaces, but still allow selected substitutions
* Any sequence of filename characters
? Exactly one filename character
[abc] One character from the set
[!abc] One character outside the set
*.{jpg,png,gif} Any listed suffix

The shell expands patterns before starting the command:

rm *~
ls /etc/*.conf
cp files/* /mnt/flash
Detailed notes - 1.2.6: Commands and arguments

1

; separates commands executed one after another

  • separator belongs to shell syntax, not to either command's arguments

2

first word = command name; remaining words = arguments

  • shell supplies strings; command decides their meaning
  • echo prints its arguments

3

unquoted spaces separate words; extra separator spaces do not become argument data

  • interactive Tab normally requests completion
  • filenames containing spaces require a way to preserve those spaces

4

three ways to protect special characters:

  • backslash before character
  • single quotes around text
  • double quotes around text
  • quoting / escape syntax removed before arguments reach the program
  • protected ; is literal data rather than a command separator

5

single quotes preserve every enclosed character literally

  • a single quote cannot be escaped inside that quoted region
  • use another quoting / escaping context to include it

double quotes retain some special processing

  • variable / command substitution and selected backslash escapes still work
  • interactive history behaviour depends on shell

6

quoted and unquoted adjacent fragments form one word

  • "abra"schwabra'kadabra' -> abraschwabrakadabra
  • "" or '' supplies an empty argument
Quoting preserves a single argument while an unquoted filename pattern expands into matching names.
From command text to argument strings. Open full size - Editable SVG
Detailed notes - 1.2.7: Filename patterns

1

shell expands unquoted filename patterns before running command

  • ? matches one character; * matches any string, including empty
  • ??? = three-character name; ???* = at least three characters
  • *.txt = names ending in .txt
  • one pattern can become many separate arguments

2

command receives expanded names, not instructions to expand a pattern

  • echo * prints names even though echo itself does not operate on files
  • patterns also work in paths, such as /etc/*.conf

3

[...] matches one member of a character set

  • img_27[234]?.jpg selects specified third digits
  • [!_]*.c excludes names beginning with _

4

brace alternatives generate several candidate patterns in shells supporting them

  • *.{jpg,png,gif} supplies patterns for three suffixes

5

unmatched patterns depend on shell behaviour

  • Bourne-style behaviour described here leaves the word unchanged
  • do not assume all shells / settings do the same

Efficient Shell Use

Key / command Action
Tab Complete a name; press twice to list alternatives
Up, Down Move through command history
Ctrl-R Search history backward
history | less Browse saved commands
!! Repeat the previous command
!137 Repeat history entry 137
Ctrl-C Cancel the current input or interrupt a program

Do not retype what the shell already knows.

Detailed notes - 1.2.8: Command history and filename completion

1

modern shells avoid repeatedly typing entire commands

2

Tab completes a uniquely determined name

  • ambiguous prefix: request possible completions, then type enough to distinguish
  • some shells complete command-specific arguments too

3

history stores previous commands, often across sessions

  • Up / Down select earlier / later commands
  • ordinary cursor / editing keys modify recalled text

4

history | less displays numbered history

  • !137: command 137; !!: previous command
  • !:0: previous command word; !:1: its first argument
  • !137:2: word 2 from command 137, numbering from zero
  • !abc: latest command beginning with abc

5

Ctrl-R searches history backward by substring

  • type search text; repeat Ctrl-R for earlier matches

6

Ctrl-C cancels a confused / unwanted input line

7

practice completion and history as ordinary working habits

  • author stresses their cumulative saving of typing time

Processes and Jobs

Key / command Meaning
Ctrl-D Send end-of-file; at a shell prompt, exit cleanly
Ctrl-C Send SIGINT to the foreground process
Ctrl-\ Send SIGQUIT
Ctrl-S, Ctrl-Q Pause and resume terminal output
Ctrl-Z Suspend, not terminate, the foreground process
ps ax List processes
top Show active processes interactively
kill PID Send SIGTERM
kill -9 PID Force termination with SIGKILL

Background and foreground jobs:

updatedb &       # start in the background
jobs             # list shell jobs
kill %2          # signal job 2
bg               # continue a suspended job in the background
fg               # bring a job to the foreground

Closing a terminal window is not a reliable way to terminate its processes.

Detailed notes - 1.2.9: Controlling task execution

1

programs may run for a long time

  • distinguish normal completion from requesting / forcing termination

2

many programs read standard input until end of file

  • input stream can originate at keyboard, file or elsewhere

3

stream is the English term for a sequence of input / output data

4

Ctrl-D on an empty terminal input line produces an end-of-input indication

  • tells the reading program that current input has ended
  • at shell prompt, normally ends the shell session

5

remember Ctrl-D for completing keyboard input in later examples

6

EOF does not require a program to terminate

  • program may handle it differently, read elsewhere or be stuck

7

Ctrl-C normally interrupts the foreground program

  • Ctrl-\ requests a quit signal and may produce a core dump
  • core files contain debugging information and can occupy much space

8

Ctrl-Z does not mean terminate or end input in Unix

9

terminal flow control can look like a hang

  • Ctrl-S pauses output; Ctrl-Q resumes it

10

closing a terminal window does not guarantee that every associated program has ended

  • determine what happened to the task itself

11

process: running instance of a program, initially simplified here

  • a program can also create further processes
  • locating a stuck task requires identifying its process

12

PID uniquely identifies an existing process

  • ps lists processes; ps ax includes all in the book's Linux / BSD examples
  • ps axu adds ownership and other information
  • option conventions vary between systems

13

top displays and refreshes information about active processes

  • q exits

14

signal: notification identified by name / number

  • program can handle or ignore many signals
  • some signals cannot be intercepted

15

Ctrl-C -> SIGINT; Ctrl-\ -> SIGQUIT

  • kill PID normally sends SIGTERM
  • kill -KILL PID / kill -9 PID sends uncatchable SIGKILL
  • identify correct PID from process listing before signalling it

zombie: process has already finished but parent has not collected its status

  • cannot be killed again; remains as an entry in process table

16

uninterruptible sleep: process waiting inside a kernel operation

  • pending signal cannot take effect until that wait ends
  • unexpectedly prolonged waits may indicate storage / hardware trouble

17

book illustrates such a wait with removing storage during active copying

  • device removal before finishing / unmounting can disrupt pending I/O

18

ps state distinguishes cases

  • Z / defunct: zombie
  • D: uninterruptible sleep
  • investigate unexpectedly persistent waits
Detailed notes - 1.2.10: Background execution

1

background execution allows continued shell use while another task runs

  • useful when task needs no interactive terminal input

2

append & to start a background job

  • shell reports job number and PID; these are different identifiers
  • jobs lists shell's jobs
  • completion reports distinguish success, nonzero exit and signal termination
  • %2 identifies job 2 in shell job-control commands

3

Ctrl-Z suspends foreground job

  • bg resumes it in background
  • fg brings background / suspended job into foreground

4

Ctrl-Z pauses execution; it does not kill the program

5

background execution is useful for graphical applications

  • application uses its own window while shell remains available

Streams, Redirection, and Pipelines

Descriptor Standard stream
0 Input
1 Output
2 Diagnostics / errors
Form Effect
cmd > file Replace file with standard output
cmd >> file Append standard output to file
cmd < file Read standard input from file
cmd1 | cmd2 Send output of cmd1 to input of cmd2
cmd 2> errors Write diagnostics to errors
cmd 2>&1 Merge diagnostics into standard output
/dev/null Discard anything written to it
ls -lR | less
gcc -Wall -g myprog.c -o myprog 2>&1 | less
ls -lR / > list.txt 2> /dev/null

Small programs become more useful when their streams can be connected.

Detailed notes - 1.2.11: Redirecting input and output

1

I/O streams carry bytes between program and outside world

  • terminal, file, device, another process or network peer
  • numeric descriptors distinguish a process's open streams

2

standard stream convention:

  • 0: standard input; 1: standard output; 2: diagnostics / standard error
  • program can use these without knowing underlying source / destination

shell redirection:

  • > file: create / truncate output file; >> file: append
  • < file: read standard input from file
  • cmd1 | cmd2: first output becomes second input
  • 2> file: redirect diagnostics; 2>&1: direct descriptor 2 to descriptor 1's destination

3

less pages through a file or standard input

  • ls -lR | less allows reading a long recursive listing

4

diagnostics use a separate stream and do not enter an ordinary pipe automatically

  • gcc ... 2>&1 | less combines output and diagnostics before paging
  • redirect unwanted output to /dev/null to discard it
  • /dev contains device-file interfaces, explained later
A pipeline joins output to input, while diagnostics have their own route.
Standard streams are independent routes. Open full size - Editable SVG

Editors, Permissions, and Documentation

A programming editor must save plain text, avoid automatic paragraph formatting, and use a monospaced font. Common terminal choices include Vim, nano, JOE, and the Midnight Commander editor.

Permissions are grouped as owner, group, and others:

Bit Value File Directory
r 4 Read contents List names
w 2 Modify contents Create, rename, or remove entries
x 1 Execute Enter and access entries
ls -l /bin/cat       # -rwxr-xr-x, or 0755
chmod 644 myfile.c   # owner: read/write; others: read
chmod a+x myscript   # make a script executable
chmod go-rwx private # remove all group/other access

Use the local manual before guessing:

man ls
man 2 write     # section 2: system calls
man 3 sprintf   # section 3: C library functions

Inside man: /text searches, Space advances a page, and q exits.

Detailed notes - 1.2.12: Text editors

1

Unix offers many editors; section introduces several terminal editors

2

programming editor requirements in the book:

  • plain text files; no automatic paragraph reformatting
  • monospaced display keeps code columns aligned
  • equal runs of m and i should occupy equal width

3

Vim = improved clone of vi

  • modal interface initially unfamiliar
  • efficient text operations become useful after practice

4

emergency Vim exit without saving: Escape, then :qa! and Enter

5

vim filename opens file; missing file created when first saved

  • begins in command mode
  • insert mode accepts text; command mode interprets keystrokes as operations

6

command-mode cursor movement: h left, j down, k up, l right

  • arrow keys usually available too

7

arrow keys transmit multibyte escape sequences

  • slow connections can make these ambiguous with pressing Escape followed by commands

8

enter insert mode with i / a, or o / O for a new line below / above

  • Escape returns to command mode
  • ^ / $ move to line start / end; x, dw, dd, d$ delete different units
  • J joins lines; . repeats change; u undoes; U restores line changes

9

/text followed by Enter searches forward

  • / followed by Enter repeats previous search

10

:number followed by Enter jumps to a line

file commands:

  • :w save; :w name save under another name
  • :wq save and exit; :q exit if unchanged; :q! discard changes and exit
  • :r name insert file; :e name edit another file
  • :ls list buffers; :b N select buffer N

11

Ctrl-^ switches between recent buffers

  • :set hidden permits leaving a modified buffer without saving
  • ~/.vimrc stores startup settings

12

V selects whole lines; v selects characters

  • movement extends selected region

13

d cuts selection; y copies it; p / P pastes after / before cursor

  • deletion commands also place removed text in a register
  • yy, yw, y$ copy line, word, or remainder of line

14

vimtutor provides guided practice

15

GNU nano: free reimplementation of Pico, originally related to Pine mail editing

  • nano filename; ordinary typing immediately inserts text
  • arrow keys / navigation keys behave conventionally
  • Ctrl-F/B/P/N provide single-character movement alternatives

16

nano's help strip uses ^ to mean Ctrl

  • Ctrl-C reports current position
  • Ctrl-O writes file; Ctrl-X exits, offering to save changes

17

watch nano's prompt line above the help strip

  • saving asks for filename; confirm with Enter or supply a different name

18

nano's go-to-position command accepts line and optional column

  • book presents the Ctrl-_ shortcut

19

Ctrl-K cuts line(s); Ctrl-U inserts the cut text

  • restore at original position then insert elsewhere to copy

20

Ctrl-G / F1 displays nano help

21

JOE = Jonathan's Own Editor

  • joe filename opens file; normal typing / cursor keys edit text
  • Ctrl-K h shows help; Ctrl-K D saves; Ctrl-K X saves and exits
  • Ctrl-C exits without saving; Ctrl-Y deletes line
  • Ctrl-K B / K mark block; Ctrl-K C / M / Y copy / move / delete it
  • Ctrl-K L goes to line; Ctrl-K F searches; Ctrl-L repeats search

22

Midnight Commander: mc opens file manager

  • F4 edits selected file; Shift-F4 creates a new file

23

book recommends configuring its editor to fill tabs with spaces

  • editor Options / General controls this
  • save configuration from Midnight Commander to retain it
Detailed notes - 1.2.13: File permissions

1

bits and octal notation help explain permissions

  • return after 1.3.2 if these representations are unfamiliar

2

permission word contains three rwx groups plus three special bits

  • owner, group, others each receive read / write / execute permissions
  • ls -l shows type followed by these permissions
  • -rwxr-xr-x: ordinary file; owner can modify; others can read / execute

3

octal digit represents one rwx group

  • r = 4, w = 2, x = 1; add granted values
  • 6 = rw-, 5 = r-x, 7 = rwx
  • 0755 grants owner rwx, group / others r-x

4

leading 0 follows C's convention for writing an octal integer

5

directory permissions concern names / traversal

  • r lists names; x allows lookup / traversal
  • w with x permits creating, renaming and removing directory entries
  • deleting a name depends on directory permissions, not file-content write permission

6

common directory modes combine r and x

  • x without r allows access to a known name without listing all names

7

w and x without r allow depositing entries without listing directory

  • book describes a shared drop directory with hard-to-guess names
  • known names remain subject to permitted entry operations

8

special bits:

  • setuid 04000: executable uses file owner's effective identity
  • setgid 02000: analogous group identity; on directory, group inheritance
  • sticky 01000: restricts removal in shared directories such as /tmp
  • behaviour on other object types is system-dependent

9

chmod sets access mode

  • chmod 644 myfile.c -> owner rw-, group / others r--

10

symbolic chmod:

  • u/g/o/a select owner / group / others / all
  • + adds, - removes, = replaces selected permissions
  • r/w/x ordinary bits; s/t special bits; X conditional execute / directory traversal
  • -R applies recursively
  • book's recursive home-directory example also grants others read access
Owner, group and other permission triplets map read, write and execute to weights 4, 2 and 1.
Permission bits form three octal digits. Open full size - Editable SVG
Tests & experiments (6 files) - 1.2.13: File permissions
Section testpermissions (01-02-13)In catalog
lesiv/touch.shShell / 3 lines
#!/bin/bash

touch hello_there
root/touch.shShell / 3 lines
#!/bin/sh

touch hello_there
run0.shShell / 6 lines
#!/bin/sh

I=2
while [ $I -gt 1 ]; do
  echo $I
done
run1.shShell / 6 lines
#!/bin/bash

I=2
while [ $I -gt 1 ]; do
  echo $I
done
run2.shShell / 6 lines
#!/bin/sh

I=2
while [ $I -gt 1 ]; do
  echo $I
done
run3.shShell / 6 lines
#!/bin/sh

I=2
while [ $I -gt 1 ]; do
  echo $I
done
Detailed notes - 1.2.14: Online documentation: man

1

Unix distributions include local documentation; man displays manual pages

2

manual covers commands, system calls, library functions, file formats and concepts

  • man ls describes ls; man waitpid describes that interface
  • scroll with arrows / Space; q exits viewer

3

/ searches forward for text; repeat search without retyping text

  • ? searches backward

4

manual section disambiguates names

  • man 2 write selects system call rather than user command
  • 1 commands; 2 system calls; 3 library functions; 4 devices
  • 5 file formats; 6 games; 7 general concepts; 8 administration
  • additional installed software can introduce other section names

Shell Scripts and Environment

An executable shell script starts with a shebang naming its interpreter:

#!/bin/sh

if [ "$1" = "" ]; then
    echo "usage: $0 directory" >&2
    exit 1
fi

mkdir "$1"
echo "created: $1"
chmod +x make-dir.sh
./make-dir.sh Paris

./ is required because command names without / are searched for only in directories listed by PATH.

Variable Meaning
$0 Script name
$1, $2, ... Positional arguments
$# Number of arguments
PATH Directories searched for commands
HOME Home directory
LANG Language and locale
EDITOR Preferred text editor
env                         # show the environment
export PATH="$PATH:/sbin"   # change inherited configuration
unset MYVAR                 # remove a variable
EDITOR=joe chfn             # change one command's environment

Child processes inherit the environment of their parent.

The special parameters in a small script:

#!/bin/sh
echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"
$ sh argdemo.sh one two three
My name is  argdemo.sh
I've got  3  parameters
Here are the first three of them, in reverse order:
 three two one

Arithmetic uses $(( )); braces separate a variable name from the text after it:

I=10
I=$((I+7))
echo ${I}abs            # 17abs; $Iabs would be another, empty variable

Etude 1.10 prints M consecutive numbers starting from N, and rejects a missing argument with a message on stderr and a nonzero status:

#!/bin/sh

if [ $# -lt 2 ]; then
    printf "Error: Enter 2 parameters\n" >&2
    exit 1
fi

N=$1
M=$2
L=$(( N + M))

while [ "$N" -lt "$L" ]; do
    echo -n "$N" ""
    N=$(( N + 1))
done
echo
$ ./numbers.sh 5 3
5 6 7
$ ./numbers.sh 5; echo $?
Error: Enter 2 parameters
1

Etude 1.13 times any command and passes its exit status on:

#!/bin/sh

d1=$(date +%s)
$*
res=$?

d2=$(date +%s)

d=$((d2-d1))
echo $d

exit $res
$ ./timeit.sh sleep 1
1
$ ./timeit.sh false; echo $?
0
1
Detailed notes - 1.2.15: Bourne Shell scripts

1

script: text executed by a named interpreter

  • initial #! followed by interpreter path identifies executable script
  • #!/bin/sh selects Bourne-compatible shell
  • execute permission required for direct execution
  • simplest script is a sequence of commands, one per line

2

poem example uses echo commands in a file

  • chmod +x humpty.sh makes executable
  • ./humpty.sh explicitly identifies script in current directory

3

command names containing / are treated as paths

  • names without / are resolved as built-ins or searched in command directories
  • this permits vim / ls without spelling their full paths

4

./ converts a local short filename into an explicit relative path

  • absolute path or work/humpty.sh works too
  • current directory is not automatically searched for bare command names

5

shebang length and interpreter-argument handling have system-dependent limits

  • book warns that some systems permit only one interpreter argument

6

shell also has variables, conditions and loops

  • author advises beginners to return after learning programming fundamentals
  • shell language is mainly suited here to short command-combining programs

7

variables associate names with string values

  • assignment has no spaces around =: MYSTRING="several words"
  • quotes preserve spaces inside the value

8

$NAME substitutes variable value

  • ${NAME} separates name from following literal text

9

$((expression)) evaluates shell integer arithmetic

  • I=$((I+7)) increases I by seven

10

positional parameters describe script invocation

  • $0 invocation name; $1, $2, ... arguments; $# argument count
  • braces needed for multi-digit parameter numbers, e.g. ${12}
  • example prints its name, argument count, then three arguments in reverse order

11

inside a shell function, positional parameters refer to that function's arguments

12

$ substitution works in double quotes but not single quotes

13

exit status supplies shell truth value

  • 0 means success / true; nonzero means failure / false
  • conditions run commands and inspect their status

14

test evaluates a condition; [ is its alternative command name

  • closing ] is a required argument; spaces separate command / operands
  • -f tests regular file; -lt / -le / -gt / -ge compare integers
  • = / != compare strings

if command; then ... else ... fi selects branch

  • any command can serve as condition, including mkdir

while condition; do ... done repeats while command succeeds

  • example prints 1 through 100 and increments counter

15

for NAME in words; do ... done iterates over words

  • especially useful with expanded filename lists

16

short-circuit command combinations:

  • cmd1 && cmd2: run second only after first succeeds
  • cmd1 || cmd2: run second only after first fails

17

&& and || have equal precedence and associate left to right

  • pipelines / redirections bind more tightly
  • pipeline's status normally comes from last command in this shell model
  • parentheses group commands, e.g. pipe output of a grouped combination

18

these constructs also work at an interactive prompt

  • dedicated shell documentation covers further features
Examples & tests (9 files) - 1.2.15: Bourne Shell scripts
Book exampleBook example: argdemo.shIn catalog
argdemo.shShell / 6 lines
#!/bin/sh

echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"
Book exampleBook example: humpty.shIn catalog
humpty.shShell / 5 lines
#!/bin/sh
echo "Humpty Dumpty sat on a wall,"
echo "Humpty Dumpty had a great fall."
echo "All the king's horses and all the king's men"
echo "Couldn't put Humpty together again."
Section test15 (01-12)In catalog
test.shShell / 5 lines
#!/bin/sh -x

echo "Hello"
name="Alice"
echo "Name is $name"
Section testbash (01-02-15)In catalog
argdemo.shShell / 6 lines
#!/bin/sh
echo "My name is " $0
echo "I've got " $# " parameters"
echo "Here are the first three of them, in reverse order:"
echo "" "$3 $2 $1"

if.shShell / 7 lines
#!/bin/sh

if mkdir new_dir; then
  echo "Directory created"
else
  echo "Failed to make new directory"
fi
loop.shShell / 7 lines
#!/bin/sh

I=1
while [ $I -le 100 ]; do
  echo $I
  I=$((I+1))
done
loop1.shShell / 5 lines
#!/bin/sh

for C in $(ls); do
  echo $C
done
try.shShell / 3 lines
#!/bin/sh

echo 'hi'
var.shShell / 9 lines
#!/bin/sh

I=10
MYFILE=/tmp/the_file_name
MYSTRING="Here are several words"

echo $I $MYFILE $MYSTRING
I=$((I+7))
echo ${I}abs
Detailed notes - 1.2.16: Environment variables

1

environment: collection of NAME=value strings available to a program

2

each process has its own environment

  • can add, change or remove entries
  • child normally inherits environment from parent

3

common variables:

  • PATH: command-search directories
  • HOME: user's home directory; LANG: language / locale setting
  • EDITOR: preferred editor
  • env displays environment entries

4

shell imports environment entries as shell variables

  • export marks a variable for inclusion in child environments
  • ordinary new shell variables are not automatically exported
  • export NAME=value combines assignment with export

5

unset removes a variable

  • changing shell environment affects subsequently launched children
  • NAME=value command supplies a setting for one invocation
  • EDITOR=joe chfn illustrates choosing an editor for a particular command

Session Logging and Unix Graphics

Record a terminal session:

script my_protocol.txt
# run commands and programs
# press Ctrl-D to finish
Detailed notes - 1.2.17: Recording a session

1

script filename starts a terminal-session transcript

  • records displayed input / output while commands run
  • Ctrl-D ends the nested shell and finishes recording
  • resulting file includes session start / end information and dialogue
Detailed notes - 1.2.18: Unix graphical subsystem

1

section describes the X Window System architecture used in the book

  • graphical facilities supplied by user programs above the OS

2

correct name: X Window System; Window is singular

3

X server manages display service

  • graphical applications send requests as X clients

4

window manager is a special X client

  • handles borders, titles, placement and resizing
  • application draws its own content area

5

window manager can be replaced while applications remain running

6

xterm is an X client emulating a text terminal

  • several windows can host separate shells for editing, compiling and testing

7

startx normally invokes xinit to start a graphical session

8

book also describes remote sessions through xdm

  • applications run on server machine; local machine provides X display

9

startup configuration determines which window manager runs

10

~/.xinitrc is a startup shell script for xinit

  • xinit starts X server, prepares environment and runs script
  • script completion ends session
  • xterm & starts terminal without waiting; foreground twm keeps session alive

11

graphical login may use ~/.xsession

  • unlike startx from an existing shell, login must establish session environment
  • sourcing ~/.profile and ~/.xinitrc can share configuration

12

window managers differ from full desktop environments

  • desktop environments add desktop metaphor and supporting services
  • book lists both categories as choices

13

a desktop environment may contain a separate window-manager program

  • its components need not work independently

14

book traces desktop metaphor to Xerox PARC research and Xerox Alto

15

book's historical survey follows later adoption in personal computers

  • graphical usability depended partly on improving hardware speed

16

many distributions provide a desktop environment by default

  • book links this to familiar interfaces for migrating users

17

author objects to desktop environments consuming resources needed by applications

18

desktop environments may create conventional user directories automatically

  • desktop directory contents can appear as icons
  • localized / spaced names require appropriate handling in shell commands

19

author recommends trying lightweight managers to support command-line study

  • IceWM offered as initial example; experimentation encouraged

20

graphical login may expose a session-type selector

  • otherwise configure appropriate startup file
  • example starts xterm in background and IceWM in foreground

21

book calls twm / fvwm-style managers classical

  • contrasts their behaviour with click-to-focus / raise interfaces

22

focus can follow pointer without raising window

  • type into a partly obscured window without rearranging all windows

23

behaviour is configurable; exact gestures depend on chosen configuration

24

find root-window menu and start a terminal

  • xterm & starts another terminal while preserving current shell availability

25

xterm options configure appearance

  • -bg black -fg gray is the book's colour example

26

title / frame gestures raise, lower, move and resize windows

  • corners commonly resize; title commonly moves

27

window-list menu helps locate hidden windows

28

virtual screens organize larger sets of windows

  • some managers treat them as adjacent regions of one larger desktop
  • a window may extend beyond one physical-screen region

29

X selection provides text transfer between applications

  • select text; middle-click pastes selection
  • clipboard copy / paste may be a separate parallel mechanism
  • mouse wheel press often acts as middle button; Shift-Insert may paste

X Window keeps graphical responsibilities separate:

application (X client) -> X server -> display and input devices
window manager         -> borders, titles, placement, virtual desktops

A Little Bit of Mathematics

Programming relies heavily on discrete mathematics: finite choices, numeral systems, logic, and computability. The important habit is not memorizing formulas, but seeing what is being counted or transformed.

Detailed notes - 1.3: Some mathematics

1

discrete mathematics supplies prerequisites for later programming material

  • chapter develops the needed reasoning rather than assuming school coverage

Combinatorics

Combinatorics counts possibilities. The safest method is:

  1. split the situation into choices
  2. multiply independent choices
  3. divide when the same result has been counted several times

If each of kk independent positions has nn possible values, then there are

n⋅n⋯n⏟ktimes=nk \underbrace{n \cdot n \cdots n}_{k\ \text{times}} = n^k

different strings. For example, nn independent yes/no choices give 2n2^n possibilities. This is also why a set of nn elements has 2n2^n subsets: for each element we choose either "take it" or "do not take it".

For permutations, the number of choices decreases by one after every pick:

n!=n⋅(n−1)⋅(n−2)⋯2⋅1 n! = n \cdot (n-1) \cdot (n-2) \cdots 2 \cdot 1

There is one empty ordering, so 0!=10! = 1. That convention makes formulas work at the boundary.

Ordered selection of kk distinct items from nn items:

P(n,k)=n⋅(n−1)⋯(n−k+1)=n!(n−k)! P(n,k) = n \cdot (n-1) \cdots (n-k+1) = \frac{n!}{(n-k)!}

The first form shows the reason: choose the first item in nn ways, the second in n−1n-1 ways, and so on.

Unordered selection removes the order after counting ordered selections:

C(n,k)=(nk)=P(n,k)k!=n!k!(n−k)! C(n,k) = \binom{n}{k} = \frac{P(n,k)}{k!} = \frac{n!}{k!(n-k)!}

Each unordered group of kk items was counted once for every internal ordering of those kk items, namely k!k! times.

Edges in a complete graph of nn vertices:

n(n−1)2 \frac{n(n-1)}{2}

From each vertex we can go to n−1n-1 other vertices, so n(n−1)n(n-1) counts directed endpoints. An undirected edge is seen twice, once from each end, so we divide by 22.

Useful binomial identities:

(n0)=(nn)=1 \binom{n}{0} = \binom{n}{n} = 1

(nk)=(nn−k) \binom{n}{k} = \binom{n}{n-k}

(n+1k)=(nk)+(nk−1) \binom{n+1}{k} = \binom{n}{k} + \binom{n}{k-1}

∑k=0n(nk)=2n \sum_{k=0}^{n} \binom{n}{k} = 2^n

Why they hold:

The recurrence builds Pascal's triangle. Row nn contains the coefficients of the binomial expansion:

(a+b)n=∑k=0n(nk)an−kbk (a+b)^n = \sum_{k=0}^{n} \binom{n}{k} a^{\,n-k} b^k

The coefficient (nk)\binom{n}{k} appears because, when multiplying (a+b)(a+b) by itself nn times, the term an−kbka^{n-k}b^k is formed by choosing the kk factors from which the bb is taken.

Detailed notes - 1.3.1: Elements of combinatorics

1

combinatorics counts possible choices / arrangements of finite sets lamp example: fixed lamps independently on or off

  • one lamp gives two distinguishable signals
  • three lamps will give eight; explanation matters more than memorized answer

2

second lamp doubles possibilities

  • first lamp's two states with second off
  • same two states with second on -> four distinct combinations

3

each additional independent two-state lamp doubles count again

  • three lamps: 8; four: 16
  • N existing signals -> 2N after adding one lamp

4

zero-lamp case clarifies what is being counted

  • a signal groups many real situations rather than describing every detail

5

no lamps gives one distinguishable configuration

  • all situations look the same; there are not zero possible configurations

6

n lamps -> 2^n configurations, including 2^0 = 1

7

choosing which of five ornaments to wear is the same problem

  • each item independently present / absent -> 2^5 = 32 choices

8

abstract form: n-element set has 2^n subsets

  • does not solve problems where order matters
  • towers of distinct cubes distinguish arrangements of the same selected cubes

9

four distinct cubes give 64 nonempty ordered towers of heights 1-4

  • three cubes give 15; five give 325
  • these counts are not obtained by simply taking all subsets

10

add a lamp with three states to three two-state lamps

  • each new state accompanies eight old configurations
  • -> 3 × 8 = 24
  • derive count from choices instead of applying a familiar formula blindly

11

flag example: three shapes and four decorations

  • each shape permits four decorations -> 3 × 4 = 12 flags

12

arrange possibilities as rows and columns

  • one cell per shape / decoration pair
  • multiplication counts independent choices

13

unlimited cubes of four colours, towers of heights 1-4

  • each position independently has four choices
  • 4 + 4^2 + 4^3 + 4^4 = 340

14

permutations: arrange all distinct objects in order

  • one ball: one arrangement; two balls: two arrangements

15

three balls: three choices for first, two arrangements of the remainder

  • -> six
  • lexicographic ordering sorts by first element, then second, and so on

16

k balls: choose first in k ways, arrange remaining k-1

  • M(k) = k M(k-1), starting with M(1) = 1
  • -> k! = k(k-1)...2·1

17

seven distinct balls -> 7! = 5040 permutations

18

alternative derivation: fill positions successively

  • 7 choices, then 6, then 5, ..., then 1
  • product gives same factorial

19

ordered selection of k distinct objects from n:

  • n choices, n-1 choices, ..., n-k+1 choices
  • count = n!/(n-k)!, also called falling factorial (n)_k
  • three of seven on a shelf -> 7 × 6 × 5 = 210

20

return to four distinct cubes

  • height 4: 24; height 3: 24; height 2: 12; height 1: 4
  • -> total 64

21

unordered selection: put three of seven balls into a bag

  • permutations of the same three balls now represent one outcome
  • each triple appears six times among 210 ordered choices

22

every three-element choice has 3! orderings

  • -> 210 / 6 = 35 unordered choices

23

general combination count: C(n,k) = n!/[k!(n-k)!]

  • first count ordered selections, then divide by k! duplicate orderings
  • book warns against applying the formula without checking what is counted

24

reconstruct formula from reasoning when needed

  • discard unused positions from n! through division by (n-k)!
  • discard order of selected elements through division by k!

25

alternative derivation: arrange all n objects, then split into two bags

  • order within first bag irrelevant -> divide by k!
  • order within second bag irrelevant -> divide by (n-k)!

26

symmetry: C(n,k) = C(n,n-k)

  • selecting objects to take is equivalent to selecting objects to leave

27

boundary cases: C(n,0) = C(n,n) = 1

  • exactly one empty choice and one choice containing everything

28

combination counts are binomial coefficients

  • (a+b)^n = sum of C(n,k) a^(n-k) b^k
  • connection comes from counting contributions to each term

29

question is which coefficient multiplies each power combination

30

distributive law multiplies every term of one sum by every term of another

  • n terms times m terms -> nm products before collecting like terms

31

expanding n factors (a+b) gives 2^n uncollected terms

  • choose a or b from each factor independently

32

term a^k b^(n-k) appears once for each choice of k factors supplying a

  • -> coefficient C(n,k)
  • a^2 b^2 appears six times in expansion of (a+b)^4

33

Pascal's triangle computes coefficients using addition

  • first / last entry in each row = 1
  • inner entry = sum of two entries above
  • C(n+1,k) = C(n,k-1) + C(n,k)

combinatorial reason:

  • choices including new object select k-1 old objects
  • choices excluding it select k old objects

34

sum of row n is 2^n

  • classifies all subsets by their sizes

35

round-robin tournament with seven players

  • each plays six others, but each game counted for both players
  • -> 7 × 6 / 2 = 21 games

36

score-sheet explanation:

  • seven players prepare six sheets each -> 42 sheets
  • two sheets submitted per game -> 21 games

37

tournament grid has one row and one column per player

  • diagonal unused; each game recorded in two opposite cells

38

49 total cells minus seven diagonal cells = 42

  • two entries per game -> 21 games

39

complete graph: every pair of distinct vertices joined by one edge

  • n vertices, n-1 incident edges per vertex
  • n(n-1) edge ends; two ends per edge
  • -> n(n-1)/2 edges

Positional Numeral Systems

In base bb, each digit is in 0,…,b−10,\dots,b-1 and each position has weight bib^i.

(dk…d2d1d0)b=dkbk+…+d2b2+d1b+d0=∑i=0kdibi (d_k \dots d_2d_1d_0)_b = d_k b^k + \dots + d_2 b^2 + d_1 b + d_0 = \sum_{i=0}^{k} d_i b^i

The rightmost digit counts units. Moving one place left multiplies the weight by bb, because one digit in that position changes the lower range by a whole block of bb possibilities.

kk digit positions represent exactly

bk b^k

values: 00 through bk−1b^k - 1. This is the same multiplication rule as in combinatorics: each of the kk positions has bb choices.

The notation changes with the base; the number itself does not.

101101102=2668=B616=18210 10110110_2 = 266_8 = \mathrm{B6}_{16} = 182_{10}

Binary groups cleanly into octal and hexadecimal because their bases are powers of two:

23=824=16 2^3 = 8 \qquad 2^4 = 16

0101101102→2668101101102→B616 010\,110\,110_2 \to 266_8 \qquad 1011\,0110_2 \to \mathrm{B6}_{16}

Convert from base bb by evaluating the digits:

15327=1⋅73+5⋅72+3⋅7+2=((1⋅7+5)⋅7+3)⋅7+2=61110 1532_7 = 1\cdot 7^3 + 5\cdot 7^2 + 3\cdot 7 + 2 = ((1\cdot 7 + 5)\cdot 7 + 3)\cdot 7 + 2 = 611_{10}

The nested form is the same formula rearranged for computation: read digits left to right, multiply the accumulated value by the base, then add the next digit.

Convert an integer to base bb by repeated division; the remainders, read in reverse order, are the digits. The reason is the division identity:

N=bq+r,0≤r<b N = bq + r, \qquad 0 \le r < b

The remainder rr is the last digit, because every higher position is a multiple of bb. Then repeat the same reasoning for the quotient qq.

103=2⋅51+151=2⋅25+125=2⋅12+112=2⋅6+06=2⋅3+03=2⋅1+11=2⋅0+1 \begin{array}{rcl} 103 &=& 2\cdot 51 + 1\\ 51 &=& 2\cdot 25 + 1\\ 25 &=& 2\cdot 12 + 1\\ 12 &=& 2\cdot 6 + 0\\ 6 &=& 2\cdot 3 + 0\\ 3 &=& 2\cdot 1 + 1\\ 1 &=& 2\cdot 0 + 1 \end{array}

10310=11001112 103_{10} = 1100111_2

For a fractional part, repeatedly multiply by bb; each resulting integer part is the next digit:

x=0.d1d2d3…bbx=d1.d2d3…b x = 0.d_1d_2d_3\dots_b \qquad bx = d_1.d_2d_3\dots_b

Multiplication by the base shifts the next digit into the integer part.

The termination rule comes from the denominator. After tt fractional digits, a terminating base-bb fraction has the form

integerbt \frac{\text{integer}}{b^t}

So a reduced denominator must divide btb^t. If it never does, the long division process eventually repeats a remainder, and the digit sequence becomes periodic.

A converter between decimal and hexadecimal, written in Pascal (chapter 2). bas2num evaluates the positional formula digit by digit:

function bas2num(h: string; b: integer): int64;
var
    i, n: integer;
begin
    bas2num := 0;
    n := length(h);
    for i := n downto 1 do
        bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;

./hex ff h converts back and prints ffh -> 255.

Show the complete program
program hex;

function pow(b, e: integer): int64;
var
    i: integer;
begin
    pow := 1;
    for i := 1 to e do
        pow := pow * b
end;

function cha2int(c: char): integer;
begin
    if ord(c) >= ord('a') then
        cha2int := ord(c) - ord('a') + 10
    else
        cha2int := ord(c) - ord('0')
end;

function int2cha(i: integer): char;
begin
    if i >= 10 then
        int2cha := chr(i - 10 + ord('a'))
    else
        int2cha := chr(i + ord('0'))
end;

function str2int(s: string): int64;
var
    i, n: integer;
begin
    n := length(s);
    str2int := cha2int(s[1]);
    for i := 2 to n do
        str2int := str2int*10 + cha2int(s[i])
end;

function bas2num(h: string; b: integer): int64;
var
    i, n: integer;
begin
    bas2num := 0;
    n := length(h);
    for i := n downto 1 do
        bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;

function num2bas(n: int64; b: integer): string;
var
    i, e: integer;
    x: int64;
begin
    e := 1;
    x := 1;
    while x > 0 do
    begin
        x := n div pow(b, e);
        e := e + 1;
    end;
    e := e - 2;

    num2bas := '';
    for i := e downto 0 do
    begin
        x := n div pow(b, i);
        n := n - x * pow(b, i);
        num2bas := num2bas + int2cha(x);
    end
end;

var
    h: string;
    n: int64;
begin
    h := ParamStr(1);
    if ParamStr(2) = 'h' then
    begin
        n := bas2num(h, 16);
        writeln(h, 'h -> ', n)
    end
    else
    begin
        n := str2int(h);
        writeln(h, ' -> ', num2bas(n, 16), 'h')
    end
end.
255 -> ffh
Detailed notes - 1.3.2: Positional numeral systems

1

position determines a digit's weight

  • radix / base n uses n digits and successive weights differing by factor n
  • decimal is the familiar base-10 instance

2

k independent positions with n possible states give n^k combinations

3

k base-n digits represent integers 0 through n^k-1

  • unused higher positions may be regarded as zero

4

adding 1 to n^k-1 exhausts k positions

  • next position becomes 1; lower positions become 0
  • its weight must therefore equal n^k

5

decimal's familiarity is historical habit

  • book stresses the relative simplicity of binary arithmetic

6

ordinary positional systems can use any integer base at least 2

  • digits have values 0 through n-1
  • 1000 in base n means n^3
  • changing representation does not change the number or its properties

7

two decimal properties generalize:

  • value = sum of digit × corresponding power of base
  • repeated division by base yields digits as remainders, least significant first

8

base-7 example: 1532 = 1·7^3 + 5·7^2 + 3·7 + 2 = 611 decimal

  • repeated division of 611 by 7 gives remainders 2,3,5,1

9

weighted sum converts from a representation to numerical value

  • repeated division constructs representation in another base

10

Horner form avoids calculating separate powers

  • process left to right: accumulated value × base + next digit
  • ((1·7+5)·7+3)·7+2 = 611

11

most-significant-first notation requires knowing total length to interpret first digit's weight

  • repeated division naturally produces digits in the opposite order

12

book relates the historical notation to Arabic writing direction

  • historical explanation presented as the book's account

13

binary is central to computer representation

  • octal abbreviates groups of three bits; hexadecimal groups of four
  • hexadecimal A-F stand for values 10-15

14

eight-bit byte -> exactly two hexadecimal digits

  • values 00 through FF = 0 through 255

15

octal fits three-bit groups rather than bytes

  • byte range 000-377; three octal digits can represent up to 511
  • octal uses only decimal digit symbols and was historically convenient

16

binary-to-decimal conversion adds powers of two at set-bit positions

  • 1001101 binary = 64 + 8 + 4 + 1 = 77

17

decimal-to-binary by repeated halving

  • record remainder at each step; read remainders in reverse
  • 103 -> 1100111; 76 -> 1001100

18

alternative: repeatedly subtract largest fitting power of two

  • mark its bit as 1; unselected powers get 0
  • 757 = 512+128+64+32+16+4+1 -> 1011110101
  • 260 = 256+4 -> 100000100

19

if one radix is the kth power of another, one digit corresponds to k smaller-base digits

20

octal / hexadecimal to binary:

  • replace each octal digit with three bits, each hexadecimal digit with four
  • preserve internal zeros; discard only unnecessary leading zeros

21

binary to octal / hexadecimal:

  • group from right into threes / fours
  • pad only leading incomplete group with zeros
  • replace each group with one digit

22

digit-group correspondences can be calculated until practice makes them familiar

23

fractional positions have weights 1/2, 1/4, 1/8, ...

  • 101.01101 binary = 5 + 13/32 = 5.40625
  • k binary fractional digits can be treated as integer numerator over 2^k

24

book uses a point to separate integer and fractional parts

  • matches notation used in programming languages

25

construct binary fractional digits by repeated multiplication by 2

  • record integer part (0 or 1), remove it, continue with remaining fraction
  • process integer part separately

26

5.40625 example:

  • integer part -> 101
  • successive fractional digits -> 01101; zero remainder ends procedure
  • trailing fractional zeros do not change value

27

a rational number has a finite base-N expansion iff its reduced denominator divides some N^k

  • decimal requires denominator with only prime factors 2 and 5
  • binary requires a power-of-two denominator

28

finite decimal fractions often become repeating binary fractions

  • detect repetition when the working remainder repeats
  • 0.35 decimal = 0.01(0110) binary

29

finite decimal fraction -> integer formed by fractional digits divided by 10^k

  • 17.325 = 17 + 325/1000 = 693/40

30

same method uses base^k in any positional system

  • binary fraction ending in 1 has odd numerator over a power of two
  • -> already reduced

31

repeating fraction: multiply by base^(period length), then subtract original

  • identical infinite tails cancel
  • solve remaining linear equation for the fraction

32

7.3(327) example:

  • separate 7.3; let x = 0.0(327)
  • 1000x - x = 32.7 -> x = 327/9990
  • restore 7.3 -> total 12209/1665

33

binary repeating example uses same procedure

  • 0.01(0110) = 1/4 + 1/10 = 7/20 = 0.35
  • multiplying repeating tail by 16 cancels a four-bit period on subtraction

34

binary addition / subtraction work column by column

  • two ones -> write 0, carry 1; three ones -> write 1, carry 1
  • borrowing from next position supplies two units in current position

35

multiplying by a power of radix appends zeros to an integer representation

  • useful when finding common denominators and adjusting numerators

36

binary multiplication simplifies ordinary long multiplication

37

each multiplier digit is 0 or 1

  • add either zero or appropriately shifted multiplicand
  • keep shifts aligned even when omitting zero rows

38

example: 110001 × 1101 binary

  • shifted copies at positions 0,2,3
  • result 1001111101 binary = 49 × 13 = 637 decimal
The same value is decomposed into binary weights and reconstructed by repeated division.
A binary numeral is a weighted sum. Open full size - Editable SVG

Binary Logic

Logical expressions produce 00 (false) or 11 (true).

xx yy x∧yx \land y x∨yx \lor y x⊕yx \oplus y x⇒yx \Rightarrow y
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 1

The operations have direct meanings:

x∧0=0,x∧1=x,x∨0=x,x∨1=1,x∧x=x,x∨x=x,x∧¬x=0,x∨¬x=1,¬¬x=x \begin{array}{rlrl} x \land 0 &= 0, & x \land 1 &= x,\\ x \lor 0 &= x, & x \lor 1 &= 1,\\ x \land x &= x, & x \lor x &= x,\\ x \land \neg x &= 0, & x \lor \neg x &= 1,\\ \neg\neg x &= x \end{array}

These identities follow from the truth table. For example, x∧1=xx \land 1 = x because the second input never blocks the value of xx, while x∧0=0x \land 0 = 0 because one false input is enough to make an AND false.

De Morgan's laws:

¬(x∨y)=¬x∧¬y \neg(x \lor y) = \neg x \land \neg y

¬(x∧y)=¬x∨¬y \neg(x \land y) = \neg x \lor \neg y

The first law says that "neither xx nor yy" is the same as "xx is false and yy is false". The second says that "not both" is the same as "at least one is false".

Other operations can be reduced to ¬\neg, ∧\land, and ∨\lor:

x⇒y=¬x∨y x \Rightarrow y = \neg x \lor y

x⊕y=(x∧¬y)∨(¬x∧y) x \oplus y = (x \land \neg y) \lor (\neg x \land y)

These formulas describe the rows where the result is true. x⇒yx \Rightarrow y is true when either xx does not happen or yy does. XOR is true in exactly two cases: x=1,y=0x=1,y=0 or x=0,y=1x=0,y=1.

A truth table completely defines a Boolean function. For nn input variables:

number of input rows=2n \text{number of input rows} = 2^n

number of Boolean functions=22n \text{number of Boolean functions} = 2^{2^n}

The first formula is the usual count of nn independent binary choices. The second follows because each of those 2n2^n rows may independently receive output 00 or output 11.

Any truth table can be converted to disjunctive normal form: for each row whose result is 11, AND together the required variables or negations, then OR all such terms.

Example term for the row x=1,y=0,z=1x=1, y=0, z=1:

x∧¬y∧z x \land \neg y \land z

That term is true on exactly that row and false everywhere else.

Detailed notes - 1.3.3: Binary logic

1

conditions in programs evaluate to true or false

  • file exists, value is in range, sufficient memory remains, etc.

2

Boolean algebra is a small part of mathematical logic

3

Boolean values: 0 false, 1 true

  • NOT reverses value: NOT 0 = 1, NOT 1 = 0
  • unary operation has one operand

4

binary operations have two operands

  • OR true if at least one operand true, including both
  • AND true only if both operands true

5

usual notation: OR written ∨; AND written & or ∧

6

XOR true when operands differ

  • unlike OR, false when both operands true

7

implication x -> y is false only for x true and y false

  • false premise makes material implication true regardless of consequent
  • book illustrates why a true conclusion alone does not establish true premises

8

Boolean function maps combinations of Boolean inputs to Boolean output

  • two inputs give four possible argument pairs
  • truth table specifies output for every pair

9

four independently chosen output bits -> 2^4 = 16 two-input functions

  • constants 0 / 1; projections x / y and negations
  • AND, OR, XOR, equivalence and implications
  • NOR = NOT OR; NAND = NOT AND
  • equivalence true exactly when operands equal

10

n inputs -> 2^n argument combinations

  • choose one output bit per combination -> 2^(2^n) functions
  • three inputs: 256; four: 65536

11

basic identities follow from operation meanings

  • x AND 0 = 0; x AND 1 = x
  • x OR 0 = x; x OR 1 = 1
  • AND sometimes written by juxtaposition, like multiplication

12

both distributive laws hold

  • (x OR y) AND z = (x AND z) OR (y AND z)
  • (x AND y) OR z = (x OR z) AND (y OR z)

13

idempotence, complements and double negation

  • x AND x = x; x OR x = x
  • x AND NOT x = 0; x OR NOT x = 1
  • NOT NOT x = x

14

De Morgan's laws:

  • NOT (x OR y) = (NOT x) AND (NOT y)
  • NOT (x AND y) = (NOT x) OR (NOT y)
  • derive by asking when original expression is false

15

reduce unfamiliar Boolean operations to AND, OR and NOT

  • implication: NOT x OR y
  • XOR: (x AND NOT y) OR (NOT x AND y)

truth-table construction of disjunctive normal form:

  • take every row with output 1
  • AND all variables, negating those that are 0 in that row
  • OR resulting terms
  • each term recognizes exactly its own input combination

Kinds of Infinity

Set Size
Natural numbers Countably infinite
Integers Countably infinite
Rational numbers Countably infinite
All finite strings over a finite alphabet AA (A*A^\ast) Countably infinite
Infinite digit strings / real numbers Uncountable; continuum

A set is countable when its elements can be assigned natural-number indices. A proper subset may have the same cardinality as the whole set: n↔2nn \leftrightarrow 2n pairs the natural numbers with the even natural numbers.

Integers are countable because they can be listed without omission:

0,1,−1,2,−2,3,−3,… 0,\ 1,\ -1,\ 2,\ -2,\ 3,\ -3,\dots

Finite strings over a finite alphabet are countable because they can be listed by length:

A*=A0∪A1∪A2∪A3∪⋯ A^\ast = A^0 \cup A^1 \cup A^2 \cup A^3 \cup \cdots

Each fixed length contains finitely many strings, so the whole list remains countable.

Cantor's diagonal argument shows that no list contains every infinite digit string: construct a new string whose digit nn differs from digit nn of item nn. The new string differs from every listed item.

For computation, the key boundary is:

Detailed notes - 1.3.4: Kinds of infinity

1

section prepares for computability discussion

  • author distinguishes intuitive algorithm concept from particular formal models

2

countably infinite set: elements can be numbered by natural numbers

  • naturals, even naturals and all integers are countable
  • integer enumeration: 0,1,-1,2,-2,...
  • countable cardinality denoted aleph-zero

3

rationals are countable too

  • enumerate integer numerator / positive denominator pairs in finite expanding layers
  • skip reducible fractions and repeated representations of zero
  • -> each rational gets one number

4

enumeration need not finish an infinite task

  • any specified rational appears after finitely many steps

5

irrational != any infinite decimal expansion

  • rational expansions can repeat forever
  • terminating / repeating behaviour depends on radix
  • irrational number cannot be written as integer ratio

6

Cantor diagonal argument shows real numbers are uncountable

  • assume a list of fractional expansions
  • construct a new expansion differing from item n at position n
  • choose digits avoiding ambiguous terminating / repeating-nine representations
  • -> new number missing from every proposed complete list

7

continuum denotes cardinality of real numbers

finite alphabet A; A* = all finite strings, including empty string

  • enumerate by length, then fixed order within each length
  • -> A* is countable

8

even an alphabet containing all symbols used in books is finite in this thought experiment

9

all finite books over that alphabet remain countable

  • includes unwritten, nonsensical and unimaginably large finite books
  • no upper length bound is needed

10

all infinite strings over an alphabet with at least two symbols form an uncountable set

  • one huge finite book differs fundamentally from the collection of infinite books

11

Graham's number illustrates magnitude without infinity

  • finite number may be far beyond practical representability
  • its finite numeral still belongs to the set of finite strings

12

infinite strings are conceptually different from even these enormous finite strings

13

author's constructive viewpoint:

  • practical finite procedures access finite portions / descriptions
  • countable enumeration promises another element, not completion of infinity

14

set theory also studies cardinalities beyond the continuum

  • power set of reals supplies an example
  • author distinguishes mathematical objects from directly executable constructions

15

continuum hypothesis: no cardinality strictly between countable infinity and continuum

  • book discusses independence from the usual set-theoretic axioms
  • answer depends on adopted axiomatic framework

Algorithms and Computability

With information encoded as finite strings, a computation has the form:

A*→A* A^\ast \to A^\ast

A*A^\ast means all finite strings over alphabet AA. Program texts are themselves finite strings, so there are only countably many possible programs. But there are uncountably many functions from A*A^\ast to A*A^\ast. Therefore most functions are not computable: there are not enough finite programs to describe them.

No single informal definition captures every reasonable constructive method. Instead, computability is studied through precise formal models:

Model Representation
Partial recursive functions Basic functions plus composition, recursion, and minimization
Turing machine Tape, states, read/write head, and transition table
Markov algorithm Ordered string-rewriting rules
Lambda calculus Function abstraction and application
Register machine Instructions operating on unbounded registers

All established general models compute the same class of functions.

Different algorithms may compute the same function. For example, the Towers of Hanoi can be solved by a recursive decomposition or by a parity-based iterative procedure. The recursive count is:

T(0)=0 T(0) = 0

T(n)=T(n−1)+1+T(n−1)=2T(n−1)+1 T(n) = T(n-1) + 1 + T(n-1) = 2T(n-1) + 1

To move nn disks, move n−1n-1 disks aside, move the largest disk once, then move the n−1n-1 disks onto it. Solving the recurrence gives:

T(n)=2n−1 T(n) = 2^n - 1

Detailed notes - 1.3.5: Algorithms and computability

1

information processing can be represented as a function on finite strings

  • choose finite alphabet A; input / result belong to A*
  • -> transformation A* -> A*

2

finite descriptions are countable; all string-to-string functions are uncountable

  • computation rules need finite descriptions
  • -> most mathematical functions have no such computable rule

3

even functions from naturals to decimal digits form an uncountable set

  • each function specifies an infinite sequence of digits
  • allowing arbitrary natural outputs does not remove the disparity

4

Boolean-valued functions on naturals correspond to subsets of naturals

  • true means membership; false means nonmembership
  • -> power set of naturals is uncountable

5

program embodies a constructive procedure / algorithm

  • programmer supplies rules precise enough for independent execution
  • a function is computable when such a rule computes it

6

author objects to school definitions treating a short verbal description as a complete account

  • emphasizes distinction between informal effective procedure and a fixed formal definition

7

computability theory grew from questions of algorithmic solvability

  • Hilbert's problems, especially the tenth problem, motivated formal investigation
  • Gödel, Kleene, Church and Turing contributed central models

8

book narrows its treatment to discrete representations

  • arbitrary real values cannot all be supplied as finite input descriptions

9

natural-number functions suffice for encoded countable domains

  • replace each finite object by its enumeration number

10

uncountably many natural-number functions still exceed countably many finite procedures

11

partial recursive functions:

  • start from simple functions: constants, successor and projections
  • build through composition, primitive recursion and minimization
  • partial functions may be undefined for some inputs
  • recursive here describes the formal construction, not only self-calling procedures

12

many proposed computation formalisms yield the same class

  • extra-looking operations can be simulated by existing ones

13

Church's thesis identifies effectively computable functions with partial recursive functions

  • a thesis connecting informal effectiveness to a formal class
  • not a theorem about two already formalized definitions

14

author emphasizes the distinction between evidence for a thesis and formal proof

  • hypothetical stronger effective model would challenge the thesis

15

book compares this thesis with an empirical hypothesis

  • author's philosophical interpretation invokes Popper's falsifiability criterion

16

algorithm theory similarly studies effective transformations of finite words

  • finite descriptions constrain the class of procedures
  • distinct algorithms may compute the same function

17

Turing machine model:

  • unbounded tape, finite alphabet and finite control states
  • transition chosen from current state and scanned symbol
  • write symbol, change state, move left / right / remain
  • initial input on tape; halting state leaves output representation

18

Turing thesis connects effective algorithms with Turing-machine computation

  • Markov algorithms, register machines, multiple-tape machines and other standard models can simulate each other

19

formal equivalence of particular models is provable

  • claim covering every intuitive effective procedure remains a thesis

20

encoding strings as natural numbers connects both approaches

  • Turing-computable and partial-recursive functions coincide under suitable encodings

21

function identity depends on input / output behaviour

  • algorithm identity also concerns method
  • same computed function does not force same algorithm

22

Towers of Hanoi:

  • three pegs; differently sized disks initially stacked largest below smallest
  • move one top disk at a time; never put larger disk on smaller
  • transfer entire stack to target with minimum moves

23

recursive solution for N disks:

  • N=0: do nothing
  • move N-1 from source to spare
  • move largest from source to target
  • move N-1 from spare to target
  • -> 2^N-1 moves

24

input = disk count; output = pairs of source / destination peg numbers

  • detailed programs appear later

25

recursive core is short

  • input parsing / validation adds surrounding program text

26

iterative Hanoi solution:

  • odd moves: smallest disk goes around pegs in fixed direction
  • even N: 1->2->3->1; odd N: 1->3->2->1
  • even moves: unique legal move between pegs not holding smallest disk

27

iterative description is short for a human but needs more state in a program

  • track each peg's stack to determine legal move
  • recursive procedure knows required moves without storing full configuration

28

two implementations produce same move sequence for same input

  • equivalent behaviour, different procedures

29

computability and algorithm theory study closely related effective transformations

  • encodings connect string and natural-number formulations
  • combined statement often called Church-Turing thesis

30

author reiterates objection to presenting informal algorithm as completely captured by a school definition

31

absence of one universal informal definition does not prevent useful work

  • formal models provide precise mathematical treatment
  • remember role of Church-Turing thesis when relating them to effective computation

Algorithm Properties

Properties expected of every algorithm:

Property Meaning
Finite objective representation It can be recorded as a finite description
Discreteness Data and execution decompose into discrete symbols and elementary steps
Determinism The same complete input determines the same behavior and, if execution terminates, result

Random values do not break determinism when they are treated as additional input.

Properties that are useful but not required:

The halting problem prevents a general termination test. Assume halts(P,x) can always decide whether program P stops on input x:

contradict(P):
    if halts(P, P):
        loop forever
    else:
        stop

Running contradict(contradict) produces a contradiction:

Therefore no algorithm decides termination for every program and input.

Detailed notes - 1.3.6: Algorithms and their properties

1

book distinguishes properties assumed of its algorithm model from properties particular procedures may have

2

objective finite representation:

  • algorithm can be written as finite text
  • finite description does not imply finite execution on every input

3

discreteness: computation proceeds through distinguishable steps / representations

  • symbolic expressions can represent irrational answers
  • quadratic solver may output (1 ± sqrt(5))/2 without storing an infinite decimal expansion

4

geometric / physical representation of sqrt(5) differs from finite symbolic encoding

  • book contrasts continuous quantities with the discrete model being discussed

5

analog computers manipulate continuous physical quantities

  • author keeps them outside this chapter's discrete algorithm model

6

determinism in the book's model:

  • complete input determines permitted next steps
  • same complete input gives same result when computation finishes

7

random values used by a program can be regarded as additional input

8

finite representation, discreteness and determinism are assumptions of this treatment

  • intelligibility concerns representation relative to executor
  • renaming variables can change text without changing algorithm

9

generality, termination, correctness and usefulness are separate characteristics

  • book does not require every procedure to possess all of them

10

generality means handling a family of inputs

  • constant-output procedure still an algorithm
  • Hello, world illustrates a useful teaching example without varying input

11

analogy: a property of a special class of triangles need not hold for all triangles

12

confusing universal assumptions with optional properties leads to misleading claims

13

book rejects treating guaranteed termination with a correct result as prerequisite for discussing a procedure

14

correctness must be judged against intended behaviour / requirements

  • author stresses disagreements between programmer and user and limits of testing
  • section's sweeping claims about verification express the author's position

15

halting / applicability problem:

  • given program and input, determine whether execution finishes
  • no algorithm decides this correctly for every possible pair

16

self-halting problem is sufficient for contradiction

  • ask whether a program halts on its own description

17

proof assumes a universal decider and derives an impossibility

  • A(W) denotes running A on input W

18

assume S(X) decides whether X(X) halts

construct D(X):

  • if S(X) says halts, loop forever
  • otherwise stop

19

apply D to its own description

  • if S(D) says halts, D(D) loops
  • if S(D) says loops, D(D) stops
  • -> either answer wrong; assumed S cannot exist

20

general halting decider would also solve self-halting

  • -> general problem undecidable

21

formal proof must distinguish program from its encoding and fix computation model

  • simplified presentation keeps main diagonal argument visible

22

termination for all inputs is also not universally decidable

  • particular programs can still have established termination proofs
  • author argues against excluding partial procedures from algorithm theory

23

undefined results are essential to the general model

  • cannot generally turn every nonterminating computation into a default output

24

diagonal argument for total functions:

  • suppose all total computable functions had an effective universal enumeration f1,f2,...
  • g(n)=fn(n)+1 would be total computable yet differ from every listed function
  • -> such an effective complete enumeration cannot exist

25

partial functions avoid that contradiction

  • if fk(k) undefined, diagonal construction also undefined there
  • resulting function need not differ from fk at its diagonal position

26

primitive recursive functions omit unbounded minimization

  • constructed through composition and primitive recursion
  • guaranteed to be defined for every natural input

27

Ackermann function gives a total computable function outside primitive-recursive class

  • grows extremely rapidly

28

book connects unrestricted loops / recursion with general partial computation

  • control-flow capability is broader than fixed bounded iteration

29

bounded loops with suitably bounded nested computation allow finite execution bounds

  • no unrestricted search / repetition remains

30

author emphasizes usefulness of unrestricted while loops and recursion

  • their availability removes automatic termination guarantees
  • individual uses can still compute total or primitive-recursive functions

31

general effective-computation models therefore admit procedures undefined on some inputs

  • distinguish this theoretical possibility from correctness requirements of a particular program

Algorithms Are Not Necessarily Action Sequences

An algorithm describes an effective computation, not necessarily an explicit ordered list of commands.

Paradigm Program describes
Imperative State-changing actions, as in C or Pascal
Functional Functions and expressions; evaluation may be lazy
Declarative / logic Required properties and relations, as in Prolog
Object-oriented Objects exchanging messages
Rewriting systems Rules for transforming symbols or terms

Formal models and programming paradigms can express equivalent computations without exposing the same action order. Every executable programming language is algorithmic; imperative and non-imperative is the useful distinction.

Detailed notes - 1.3.7: A sequence of actions is not the whole idea

1

algorithm need not be written as an explicit sequence of imperative actions

2

equivalent formal models have different representations

  • state-transition table, recursive functions, string-rewriting rules, lambda terms, register instructions
  • same computable transformations despite different notation

3

functional programming expresses values through functions

  • lazy evaluation can defer work until result required
  • written expression need not specify a straightforward execution order

4

declarative programming describes required relations / properties

  • Prolog example: facts and rules used in a proof / search process

5

object-oriented viewpoint emphasizes objects and messages

  • imperative languages such as Pascal / C describe state-changing actions
  • dominant hardware architecture helps explain popularity of imperative style

6

programs in executable languages still express effective computations

  • non-imperative does not mean nonalgorithmic
  • author's comments about heuristics / neural networks are opinions in this discussion

7

recursion even in imperative languages can obscure a direct action sequence

  • therefore surface syntax is a poor test of algorithmic character

8

use imperative / non-imperative for the intended distinction

  • reserve algorithmic for computability rather than action-list notation

9

terminology disputes should not obscure substantive mathematical results

10

a universal tool correctly detecting every nonterminating program would solve halting problem

  • -> impossible under the model just discussed

11

undecidability limits general automatic reasoning about arbitrary programs

  • does not rule out proofs about particular programs or restricted classes

12

author notes that programmers may recognize diagonal halting proof without knowing formal computability vocabulary

13

bounded versus unrestricted computation connects theory with programming practice

  • partial recursive / Turing-computable class models general programs
  • primitive-recursive constructions provide a useful restricted total class

Programs and Data

Inside a computer, programs and data are stored as bit patterns. The same bits can represent an integer, text, a floating-point number, an instruction, or part of a file; the meaning comes from the convention used to interpret them.

Measuring Information

A bit is the amount of information that cuts uncertainty in half. If a problem initially has N0N_0 equally possible variants and a message leaves N1N_1 variants, then the information gained is

I=log2N0N1 I = \log_2 \frac{N_0}{N_1}

bits. A yes/no answer gives at most one bit because it has two possible outcomes.

To guarantee finding one object among NN equally possible objects with yes/no questions, the required number of questions is

⌈log2N⌉ \lceil \log_2 N \rceil

For example:

⌈log21000⌉=10210=1024 \lceil \log_2 1000 \rceil = 10 \qquad 2^{10} = 1024

The strategy is binary search: split the remaining possibilities into two nearly equal parts at every step.

If an event has probability pp, then learning that it happened gives

I=−log2p=log21p I = -\log_2 p = \log_2 \frac{1}{p}

bits of information. Less probable events carry more information when they are confirmed.

Examples:

log23 \log_2 3

bits are needed to distinguish one of three equally likely alternatives.

log260⋅8030⋅20=log28=3 \log_2 \frac{60\cdot 80}{30\cdot 20} = \log_2 8 = 3

bits are gained when a search area shrinks from 60×8060 \times 80 to 30×2030 \times 20.

A byte normally means eight bits, also called an octet when the eight-bit size must be explicit:

1byte=8bits28=256 1\ \text{byte} = 8\ \text{bits} \qquad 2^8 = 256

So one byte can store one of 256256 different bit patterns.

Detailed notes - 1.4.1: Measuring information

1

bit = binary digit

  • computer represents information using combinations of zeros and ones

2

information reduces uncertainty

  • one bit corresponds to halving an equally likely set of possibilities
  • distinguishing one of 1000 numbers needs at most ten well-chosen yes/no questions

3

divide remaining possibilities into two equal or nearly equal groups

  • ask which group contains answer; discard other group
  • at most 1000 -> 500 -> 250 -> 125 -> ... -> 1

4

ordered interval makes the same procedure easier

  • ask whether number lies in lower or upper half
  • retain corresponding interval and repeat

5

information amount need not be an integer number of bits

  • card trick repeatedly asks which of three rows contains chosen card

6

27-card trick:

  • deal into three rows; place indicated row between other two
  • deal cyclically again; candidates now middle three cards of each row
  • repeat; third answer identifies middle card
  • gathering indicated row in middle puts chosen card fourteenth in deck

7

each three-way answer reduces candidates by factor 3

  • one trit = log2(3) bits

8

treasure-search example:

  • area shrinks from 60 × 80 to 30 × 20
  • eightfold reduction under uniform-location assumption -> log2(8) = 3 bits

9

probability example assumes independent matches

  • win probabilities 1/4 and 1/2 -> both wins probability 1/8
  • information in this outcome = -log2(1/8) = 3 bits

10

both losses probability 3/8

  • information = log2(8/3) = 3 - log2(3) bits
  • more probable event conveys less surprise

11

byte usually means eight bits; historical machine usage varied

  • octet unambiguously means exactly eight bits

12

eight bits give 256 patterns

  • can represent unsigned 0-255 or signed -128-127
  • one-byte character codes suffice for limited alphabets, not all writing systems

13

adjacent memory locations form a region for larger values

  • same storage also holds program instructions

14

memory does not record the intended interpretation of bytes

  • 41 4E 4E 41 hexadecimal can be read as ANNA, integer, float or instructions
  • operation / program context determines interpretation

15

large information units have historically ambiguous decimal / binary usage

  • KB, MB, GB etc. require attention to convention

16

N binary address lines distinguish 2^N memory locations

17

installed memory can be smaller than address space

  • bank selection and location selection divide address bits

18

memory capacities naturally relate to powers of two

  • several banks need not themselves total one power of two

19

historical K meant 1024 locations / words, close to decimal thousand

  • 8192-location bank = 8 K; three such banks = 24 K

20

smaller addressable bytes allowed multiple characters per machine word

  • byte-based capacity notation later became common

21

binary usage extended to 2^20, 2^30, 2^40 bytes

  • storage manufacturers also used decimal powers consistent with SI prefixes

22

difference between decimal and binary interpretations increases with exponent

  • small at kilo scale, substantially larger at tera scale

23

communication rates conventionally use decimal multiples of bits per second

  • link transmission does not inherently follow memory's binary capacities

24

binary prefixes remove ambiguity

  • Ki = 2^10, Mi = 2^20, Gi = 2^30, Ti = 2^40
  • B denotes byte; bit denotes bit
  • GiB means 2^30 bytes

25

book describes slow adoption and continued historical usage

  • especially when discussing RAM

26

unambiguous meaning is the advantage of KiB / MiB / GiB notation

Machine Representation of Integers

Real machines allocate a fixed number of bits for an integer. With kk bits, unsigned arithmetic has exactly

2k 2^k

different bit patterns, interpreted as

0,1,…,2k−1 0,\ 1,\ \dots,\ 2^k-1

If a result does not fit, the extra carry is lost and arithmetic wraps around:

(2k−1)+1≡0(mod2k) (2^k - 1) + 1 \equiv 0 \pmod{2^k}

For k=8k=8:

111111112=255255+1≡0(mod256) 11111111_2 = 255 \qquad 255 + 1 \equiv 0 \pmod{256}

When an integer occupies several bytes, architectures choose a byte order:

Order Memory layout for 00001D4C1600001D4C_{16}
Big-endian 00 00 1D 4C
Little-endian 4C 1D 00 00

The value is the same; only the order of bytes in memory changes.

Signed integers are usually stored in two's complement. The same kk-bit pattern has signed value

signed(u)={u,0≤u<2k−1,u−2k,2k−1≤u<2k, \operatorname{signed}(u) = \begin{cases} u, & 0 \le u < 2^{k-1},\\ u - 2^k, & 2^{k-1} \le u < 2^k, \end{cases}

where uu is the unsigned interpretation of the bit pattern.

Thus the representable signed range is

−2k−1,…,2k−1−1 -2^{k-1},\ \dots,\ 2^{k-1}-1

For eight bits:

100000002=−128011111112=127 10000000_2 = -128 \qquad 01111111_2 = 127

To change the sign in two's complement, invert all bits and add one:

−x≡x¯+1(mod2k) -x \equiv \overline{x} + 1 \pmod{2^k}

Example for 55 in eight bits:

000001012→invert111110102→+1111110112=−5 00000101_2 \xrightarrow{\text{invert}} 11111010_2 \xrightarrow{+1} 11111011_2 = -5

The reason this works is modular arithmetic:

y−x≡y+(2k−x)(mod2k) y - x \equiv y + (2^k - x) \pmod{2^k}

The processor can therefore use the same addition circuitry for subtraction. For unsigned arithmetic, the important event is carry out of the fixed width. For signed arithmetic, the important event is overflow, when a result crosses the boundary between 011…111011\dots 111 and 100…000100\dots 000.

Detailed notes - 1.4.2: Machine representation of integers

1

mathematical integers have no largest value

  • any fixed physical representation has finite capacity

2

machine integer commonly allocated fixed width: 8,16,32 or 64 bits

  • decimal mechanical counter illustrates limited positions and carry

3

fixed-width counter eventually wraps

  • 99999 + 1 -> 00000 in five decimal positions
  • carry goes beyond available positions

4

unsigned n-bit integer range: 0 through 2^n-1

  • eight bits: 0-255; 255+1 discards carry in fixed-width hardware result
  • general radix-N, k-digit maximum: N^k-1

5

arbitrary-precision arithmetic allocates more storage as needed

  • limited by resources; extra software work compared with fixed-width operations

6

multibyte values require a byte-order convention

  • little-endian: least significant byte at lowest address
  • big-endian: most significant byte first
  • 7500 = 0x00001D4C
  • big-endian bytes 00 00 1D 4C; little-endian 4C 1D 00 00

7

endian names allude to Swift's dispute over which end of an egg to open

8

signed interpretation assigns some bit patterns to negative integers

  • differs from unsigned interpretation of same storage

9

separate sign-and-magnitude complicates arithmetic

  • two's complement permits simpler common operations

10

subtract 1 from all zeros -> all ones in fixed width

  • assign all-ones pattern value -1
  • adding 1 then gives zero as required

11

n-bit two's-complement interpretation:

  • high bit 0: ordinary nonnegative value
  • high bit 1: unsigned value minus 2^n
  • range -2^(n-1) through 2^(n-1)-1
  • eight bits: -128 through 127
  • crossing signed boundary causes signed overflow

12

overflow means mathematical result does not fit representation

  • positive plus positive may appear negative after truncation, or reverse
  • wider arithmetic / explicit checks needed to preserve intended result

13

negation in two's complement: invert all bits, then add 1

  • 00000101 (5) -> 11111010 -> 11111011 (-5)
  • applying again restores 5; zero stays zero

14

most-negative value has no positive counterpart in same signed width

  • negating eight-bit -128 leaves same hardware bit pattern and overflows

15

two's-complement addition / subtraction use same bit operations as unsigned arithmetic

  • subtraction can be performed by adding negated subtrahend

16

75-19 example:

  • 75 = 01001011; -19 = 11101101
  • sum = 100111000; discard ninth bit -> 00111000 = 56

17

arithmetic explanation: invert x then add 1 gives 2^n-x modulo 2^n

  • y + (2^n-x), after discarded carry, represents y-x
Little-endian and big-endian store the same four-byte number at increasing addresses.
Byte order changes placement, not the value. Open full size - Editable SVG
A four-bit wheel shows modular arithmetic and the signed boundary; negation inverts and adds one.
The same bits have two interpretations. Open full size - Editable SVG
Section test (1 file) - 1.4.2: Machine representation of integers
Section test02 (01-04)In catalog
hex.pasPascal / 86 lines
program hex;

function pow(b, e: integer): int64;
var
    i: integer;
begin
    pow := 1;
    for i := 1 to e do
        pow := pow * b
end;

function cha2int(c: char): integer;
begin
    if ord(c) >= ord('a') then
        cha2int := ord(c) - ord('a') + 10
    else
        cha2int := ord(c) - ord('0')
end;

function int2cha(i: integer): char;
begin
    if i >= 10 then
        int2cha := chr(i - 10 + ord('a'))
    else
        int2cha := chr(i + ord('0'))
end;

function str2int(s: string): int64;
var
    i, n: integer;
begin
n := length(s);
    str2int := cha2int(s[1]);
    for i := 2 to n do
        str2int := str2int*10 + cha2int(s[i])
end;

function bas2num(h: string; b: integer): int64;
var
    i, n: integer;
begin
    bas2num := 0;
    n := length(h);
    for i := n downto 1 do
        bas2num := bas2num + cha2int(h[i]) * pow(b, n - i);
end;

function num2bas(n: int64; b: integer): string;
var
    i, e: integer;
    x: int64;
begin
    e := 1;
    x := 1;
    while x > 0 do
    begin
        x := n div pow(b, e);
        e := e + 1;
    end;
    e := e - 2;

    num2bas := '';
    for i := e downto 0 do
    begin
        x := n div pow(b, i);
        n := n - x * pow(b, i);
        num2bas := num2bas + int2cha(x);
    end
end;

var
    h: string;
    n: int64;
begin
    h := ParamStr(1);
    if ParamStr(2) = 'h' then
    begin
        n := bas2num(h, 16);
        writeln(h, 'h -> ', n)
    end
    else
    begin
        n := str2int(h);
        writeln(h, ' -> ', num2bas(n, 16), 'h')
    end
end.

Floating-Point Numbers

Floating-point numbers store a sign, a mantissa, and an exponent. In normalized binary form:

N=(−1)sM2P1≤M<2 N = (-1)^s M 2^P \qquad 1 \le M < 2

The sign bit ss determines the sign, MM stores the significant bits, and PP is the power of two. IEEE-754 formats usually store the exponent with a bias:

E=P+BP=E−B E = P + B \qquad P = E - B

For a normalized value with mm stored mantissa bits:

N=(−1)s(1+F2m)2E−B N = (-1)^s \left(1 + \frac{F}{2^m}\right) 2^{E-B}

where FF is the integer represented by the stored mantissa field.

Common IEEE-754 formats:

Format Total bits Exponent bits Mantissa bits Bias
Single precision 32 8 23 127
Double precision 64 11 52 1023

Floating-point operations are approximate because the mantissa has finite length. Addition can require shifting one mantissa right to match exponents, and the shifted-out bits are lost.

Do not treat floating-point arithmetic like exact integer arithmetic:

110 \frac{1}{10}

has a finite decimal notation, but not a finite binary notation. Its stored floating-point value must be rounded. For this reason, testing two floating-point results for exact equality is often the wrong test.

Detailed notes - 1.4.3: Floating-point numbers

1

normalized binary floating point: N = (-1)^s M·2^P

  • sign s, significand / mantissa M, exponent P
  • ordinary normalized nonzero values use 1 <= M < 2
  • book discusses common IEEE-754 binary formats

2

leading 1 of normalized significand need not be stored

  • stored exponent uses bias
  • binary64: 1 sign bit, 11 exponent bits with bias 1023, 52 fraction bits
  • special cases / subnormal numbers deferred here

3

addition / subtraction aligns exponents by shifting smaller significand

  • calculate result, then normalize by adjusting significand and exponent together
  • multiplication / division also require normalization

4

finite precision introduces rounding

  • shifts or conversion can discard significant bits
  • values such as 1/10 have infinite repeating binary representations
  • computations generally approximate real arithmetic
  • exact equality after rounded computation may not match mathematical expectation

5

integer calculations within representable range remain exact

  • do not generalize floating-point rounding to all computer arithmetic

Texts, Languages, and Encodings

Text is convenient for people, but unrestricted natural language is extremely hard for programs to analyze. A formal language is a set of strings built according to explicit rules:

L⊆A* L \subseteq A^\ast

where AA is an alphabet and A*A^\ast is the set of all finite strings over that alphabet.

Formal languages range from very small data formats to programming languages:

Language kind Purpose
Data format Describe data in a program-readable way
Markup language Describe text structure or presentation, as in HTML
Programming language Describe algorithms or computations

Some programming languages are algorithmically complete: any algorithm can be expressed in them, assuming unlimited memory and time.

Text is still stored as numbers. An encoding maps characters to byte sequences. ASCII is a seven-bit character set:

27=128 2^7 = 128

codes, enough for English letters, digits, punctuation, control characters, and basic technical symbols. The historical association "one byte = one character" came from storing ASCII characters in eight-bit bytes.

Unicode is not itself one encoding; it is a registry of characters and their code points. Encodings based on Unicode include UTF-8, UTF-16, and UTF-32.

UTF-8 keeps ASCII compatibility and uses variable-length byte sequences:

First byte pattern Total bytes Payload bits
0xxxxxxx 1 7
110xxxxx 2 11
1110xxxx 3 16
11110xxx 4 21

Continuation bytes start with 10xxxxxx. UTF-8 has three practical advantages:

The tradeoff is that the nn-th character cannot always be reached by jumping to byte nn, because characters have variable byte length.

Detailed notes - 1.4.4: Texts and languages

1

natural-language text can describe a very wide range of information

2

natural-language analysis distinguishes morphology, syntax and semantics

  • ambiguous word forms require context
  • book describes semantic understanding as particularly difficult

3

author argues that neural-network language behaviour differs from explicit semantic analysis

  • discussion expresses the book's interpretation of contemporary AI

4

author stresses difficulty of explaining / correcting unexpected learned-system behaviour

  • his assessment is a viewpoint, not a programming-language definition

5

formal constraints make automatic analysis more manageable

  • users express information according to specified rules

6

formal language: language governed by explicit construction rules

  • mathematical notation and musical notation predate computers

7

for syntactic analysis, language can be viewed as a set of accepted strings

  • this abstraction does not by itself describe meaning / semantics

8

language design balances expressive needs and analysis complexity

  • measurement file might allow only numbers and separators
  • programming languages need richer constructions

9

storing / transmitting / displaying natural-language text does not require understanding its subject

  • editors, email and typesetting illustrate this distinction

10

ELIZA illustrates conversation produced through pattern manipulation

  • uses structure and words of input to construct replies
  • apparent conversational ability does not by itself reveal underlying method

11

many programming languages have been created; active communities maintain only some

12

markup languages describe document structure / presentation

  • HTML is the book's example; distinguish markup from general programming

13

any text-input program implicitly determines a language of accepted inputs

  • this language may be simple and unnamed

14

classification as programming can have disputed boundaries

  • SQL queries illustrate dependence on what is meant by a program

15

Turing-complete language can express a simulator of a Turing machine

  • provides a precise notion of computational expressive power
  • some languages designed for other purposes, such as TeX, are also Turing-complete
Detailed notes - 1.4.5: Text as a data format; encodings

1

text content and its stored representation are different

  • editors may save the same content in different formats

2

plain text uses character encodings without a document application's private formatting structures

  • ASCII originated as a code for interchange / teleprinter use
  • includes letters, digits, punctuation and control codes

3

ASCII uses seven bits -> 128 codes

  • 0-31 controls; 9 tab, 10 line feed, 13 carriage return
  • 32 space; decimal digits occupy 48-57
  • digit code minus 48 gives its numerical value

4

uppercase A-Z: 65-90; lowercase a-z: 97-122

  • corresponding ASCII letter cases differ by bit value 32

5

printable ASCII ends at 126 (~); 127 is DEL / RUBOUT

  • all-one punched-tape pattern could erase an existing character by punching remaining holes

6

eight-bit storage encouraged one-byte-per-character encodings

  • upper 128 codes used for incompatible national extensions
  • KOI8 Cyrillic order differs from alphabetic order

7

KOI8 positions preserve rough Latin transliteration if high bit is lost

  • explains unusual ordering and historical communication use
  • ё placed outside main contiguous Cyrillic region

8

CP866: DOS-era Cyrillic encoding

  • pseudographic symbols interrupt lowercase range
  • existing legacy data / interfaces can still use it

9

CP1251: another Cyrillic mapping associated with Windows

  • includes several Slavic alphabets; not every Cyrillic-using language

10

MacCyrillic and ISO 8859-5 are further distinct mappings

  • book's statements about their prevalence reflect its historical discussion

11

properties motivating simple byte-oriented text:

  • easy concatenation / splitting, direct byte indexing, human readability
  • no machine-word size or integer-byte-order dependency

Unicode separates character repertoire / code points from particular encodings

  • UCS-2, UTF-32, UTF-8 and UTF-16 represent this repertoire differently

12

UCS-2 uses fixed two-byte values and cannot represent whole Unicode repertoire

  • UTF-32 uses four-byte code units; storage overhead is author's main objection

13

multibyte code-unit formats require attention to byte order and boundaries

  • BOM may identify byte order
  • arbitrary byte slices / concatenations need not be valid encoded text

14

UTF-8 is byte-oriented and preserves ASCII codes 0-127

  • non-ASCII Unicode code points use multibyte sequences
  • current Unicode UTF-8 uses one to four bytes; book also mentions obsolete longer forms

15

UTF-8 prefixes identify sequence structure

  • 110xxxxx: two-byte lead; 1110xxxx: three-byte lead; 11110xxx: four-byte lead
  • following bytes start 10xxxxxx
  • payload capacities: 11,16,21 bits respectively

16

UTF-8 has no integer-byte-order dependency

  • slicing must respect character boundaries
  • variable byte length prevents direct character indexing by byte offset
  • correct display also needs suitable font glyphs

17

UTF-16 uses one or two 16-bit code units per Unicode scalar value

  • combines variable length with byte-order concerns
  • book strongly prefers UTF-8 and discusses historical Windows use

18

author recommends ASCII for portable program text in this course

  • broader encodings require attention to decoding, tooling and display support

Binary and Text Data

Text data is represented in a form meant to be read and edited by humans. Binary data usually stores values in the same compact representation used inside memory.

For 100100 four-byte integers, the binary size is fixed:

100⋅4=400bytes 100 \cdot 4 = 400\ \text{bytes}

The text representation depends on the number of digits and separators. For the sequence 1000,2001,3002,…,1000991000, 2001, 3002, \dots, 100099, written one number per line:

9⋅4+90⋅5+1⋅6+100=592 9\cdot 4 + 90\cdot 5 + 1\cdot 6 + 100 = 592

bytes. The final 100100 counts newline characters.

Binary is compact and easy for programs to read after they know the format. Text is larger and requires parsing, but it is portable, inspectable, and works well with standard Unix tools.

Use hexdump -C file to inspect bytes directly. In a dump:

For little-endian four-byte integer data, bytes

e8 03 00 00

represent

000003E816=3⋅162+14⋅16+8=1000 000003E8_{16} = 3\cdot 16^2 + 14\cdot 16 + 8 = 1000

after reversing the byte order to read the numeric value.

Detailed notes - 1.4.6: Binary and textual data

1

text representation is directly readable by humans

  • binary representation uses another agreed encoding, often close to in-memory values

2

example writes 100 integers: 1000,2001,...,100099

  • four-byte binary values -> 400 bytes
  • decimal text, one value per line -> 592 bytes
  • 9 four-digit + 90 five-digit + 1 six-digit values + 100 newlines
  • text size depends on number of digits, so need not always exceed binary size

3

text file can be inspected with cat or edited with an ordinary text editor

4

printing binary bytes as characters produces meaningless output

  • embedded terminal control sequences may alter terminal behaviour
  • reset can restore terminal settings

5

hexdump -C shows offsets, hexadecimal byte values and printable-character view

  • offsets advance by 16 bytes per displayed row
  • unprintable bytes represented by dots in character view

6

decode example using agreed four-byte little-endian format

  • e8 03 00 00 -> 0x000003e8 -> 1000
  • 03 87 01 00 -> 0x00018703 -> 100099

7

hexdump of text shows digit codes rather than binary integer values

  • 31 30 30 30 0a = characters 1000 followed by newline

8

computation requires converting numeric text to the machine's numeric representation

  • keep track of which representation each value currently has

Machine Code, Translators, and Assembly

A CPU executes machine code: numeric codes for machine instructions stored in memory. The instruction pointer tells the CPU where the next instruction is.

Human programmers rarely write raw machine codes. A translator bridges the gap:

Tool What it does
Compiler Translates source text into another representation, often machine code
Interpreter Executes source text or an internal representation while it remains in memory
Assembler Translates assembly mnemonics into machine instructions

A compact distinction:

The boundary is not always clean: interpreters may compile internal bytecode, and compilers may leave support code for runtime services. The practical question is whether the translator must remain present while the user program runs.

Assembly language replaces numeric machine-code bytes with mnemonics. For example, a processor instruction encoded as bytes can be written as

add eax, ebx

The assembler translates the mnemonic form to the exact machine-code bytes. Unlike a high-level compiler, an assembler has very little freedom: assembly source is already a near-direct description of the machine instructions.

Detailed notes - 1.4.7: Machine code, compilers and interpreters

1

computer consists of CPU, memory and peripheral devices

  • introductory model connects them through bus / controllers

2

memory locations have addresses and fixed-width stored patterns

  • eight-bit location has 256 possible states

3

registers provide fast, limited CPU-local storage

  • CPU transfers data between registers and RAM and performs operations

4

machine word describes natural processor data width

  • often spans several addressable bytes
  • book's Pentium example uses 32-bit words and eight-bit bytes

5

instruction pointer and fetch / decode / execute cycle control execution

6

machine code consists of CPU instruction encodings

  • 01 D8 on the book's x86 example adds EBX to EAX
  • operand bits encode register choices and addressing form

7

manually constructing / decoding large streams of numeric instruction codes is impractical

8

high-level source expresses operations in a form convenient for humans

  • execution requires an implementation such as compiler or interpreter

9

compiler translates source to another representation

  • course example: Pascal source -> executable machine code
  • compiler reports syntax errors or produces executable
  • OS loads executable and transfers control to its code

10

compiler itself is a program

  • self-hosting compiler can be compiled by an earlier version of itself

11

interpreter reads a program and performs its prescribed operations

  • may first build a convenient internal representation
  • need not generate machine code for interpreted program

12

JIT compilation generates machine code during execution

  • distinct implementation technique, not definition of ordinary interpretation
  • executable-memory management adds implementation work

13

Bourne Shell is an already encountered interpreter

  • shell command files are programs

14

implementations can combine compilation and interpretation

  • compile to bytecode, then execute through a runtime / virtual machine
  • standalone executable may bundle interpreter plus intermediate program

15

book's practical distinction:

  • ordinary compiler can finish before resulting program runs
  • interpreter participates while interpreted program executes
  • mixed implementations and terminology make boundary less sharp

16

high-level language may not expose required processor operation / exact implementation

  • -> assembly language can specify low-level instructions

17

assembler translates symbolic instruction notation to machine code

  • add eax, ebx is a mnemonic representation of example encoding
  • names replace manual opcode / operand-bit calculations

18

high-level compiler chooses instruction sequences, registers and optimizations

  • assembly source specifies concrete machine instructions much more directly

19

readable mnemonics still leave substantial low-level work

  • one high-level statement may require many assembly instructions
  • assembler does not provide all high-level language's ready-made constructions

20

several assembly syntaxes can target same instruction set

  • Intel-style add eax, ebx versus AT&T-style addl %ebx, %eax
  • assembler directives control storage, symbols, sections and assembly-time processing
  • directive sets / syntax also vary

21

assembler is ordinary software; different authors can implement different tools

  • NASM is the x86 assembler used later in this book

The CPU repeatedly performs this cycle:

fetch instruction -> advance instruction pointer -> decode -> execute
Compiled, interpreted and bytecode execution place translation and the runtime at different stages.
Where translation and execution happen. Open full size - Editable SVG

Reading map Next: Programming in Pascal

Comments

Leave a comment Sign in All comments