electronics engineering
Course handbook · Second year · Edition with space for notes
Informatics
Computer science foundations: algorithms, data representation, programming basics and how a computer executes a program.
- 11Topics
- 0Solved exercises
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/informatics-foundations. Links work in the PDF too.
1Computer architecture
Before writing programs it helps to know what happens inside the machine that runs them. From the microcontroller in a washing machine to a data centre server, almost every computer follows the same scheme, proposed by von Neumann in 1945: a processor, a memory holding both data and instructions, and input and output devices, connected by a bus. In this lesson we see how it is built, how it runs a program and what happens when a C program is compiled.
The von Neumann architecture

- CPU (central processing unit). The ALU performs arithmetic and logic operations; the control unit reads instructions and coordinates everything else; the registers are a few very fast memory cells inside the processor. Two special registers: the program counter (PC), holding the address of the next instruction, and the instruction register (IR), holding the one being executed.
- Main memory (RAM). A long sequence of cells, each with an address. Each cell holds one byte (8 bits). It is volatile: it is wiped when power is lost.
- Input and output. Keyboard, screen, network, disk, but also sensors and actuators in an embedded system.
- Bus. The connections between the parts: address, data and control signals.
The fetch-decode-execute cycle
The processor repeats three steps forever, paced by the clock:
- fetch: read from memory the instruction at the address in the PC, and increment the PC;
- decode: the control unit interprets the instruction (which operation, on which registers or addresses);
- execute: the ALU performs the operation, and the result goes to a register or to memory.
A jump instruction changes the PC, and that is how conditions and loops are made. A 3 GHz processor runs billions of these cycles per second, and modern processors overlap several of them (pipelining) and execute several instructions at once.
The memory hierarchy
Fast memory is expensive, large memory is slow. That is why there are several levels:
| Level | Typical size | Access time |
|---|---|---|
| registers | a few hundred bytes | under 1 ns |
| L1, L2, L3 cache | tens of kB to tens of MB | 1 to 40 ns |
| RAM | gigabytes | about 100 ns |
| SSD | terabytes | about 100 µs |
| hard disk | terabytes | about 10 ms |
A hard disk access is a hundred thousand times slower than a RAM access. Caches work because programs tend to reuse data they have just used (temporal locality) and nearby data (spatial locality): walking through an array in order is much faster than jumping around memory at random.
From source code to executable
The processor understands only machine language: bit sequences encoding the instructions, different for each processor family (x86, ARM, RISC-V). Writing machine language, or its readable form, assembly, is possible but slow. That is why high-level languages such as C are used, with a compiler to translate them.
The path of a C program, for example with gcc:
- preprocessor: expands the
#includeand#definedirectives; - compiler: translates the C code into assembly and then into object code (.o files);
- linker: joins the object files together and with the libraries (such as the one containing printf) and produces the executable.
#include <stdio.h>
int main(void)
{
int a = 3, b = 4;
int c = a + b; /* becomes a few machine instructions: load, add, store */
printf("%d\n", c);
return 0;
}With gcc -S you can see the generated assembly: the sum becomes an add instruction between two registers. C is close to the machine: every construct has a predictable translation, which is why it is still the language of operating systems, drivers and microcontrollers.
Compiler and interpreter. Languages such as Python are instead interpreted: a program, the interpreter, reads the code and executes the statements one at a time. It is more convenient, but slower, often by tens of times.
Harvard and microcontrollers
Many microcontrollers, such as Arduino’s AVRs and PICs, use the Harvard architecture: separate memories and buses for instructions (Flash, non-volatile) and for data (RAM). The processor can read an instruction and a data item in the same cycle. ARM Cortex-M processors combine the two ideas: separate buses, but a single address space holding Flash, RAM and the peripheral registers, which are read and written like ordinary memory cells. This is what lets C control hardware directly, as we will see in the last lesson of the course.
2Data representation
Inside a computer everything is made of bits: numbers, letters, images, instructions. The same group of 8 bits, 01000001, can be the number 65, the letter A or part of an instruction, depending on how it is interpreted. In this lesson we see how signed and unsigned integers are represented, two’s complement, hexadecimal notation, characters and the overflow problems that follow.
The binary system
In base 2 each digit is worth a power of 2:
. To convert a decimal number to binary, divide repeatedly by 2 and read the remainders from the bottom up: 13 → 6 remainder 1, 3 remainder 0, 1 remainder 1, 0 remainder 1, so
.
With
bits you represent
values: with 8 bits (a byte) from 0 to 255, with 16 bits from 0 to 65,535, with 32 bits from 0 to about 4.3 billion.
Hexadecimal
Binary numbers are long and hard to read. Base 16 uses the digits 0-9 and A-F (A = 10, …, F = 15), and each hexadecimal digit corresponds to exactly 4 bits. Conversion is immediate, in groups of four:
| Binary | 1010 | 0011 | 1111 | 0000 |
|---|---|---|---|---|
| Hexadecimal | A | 3 | F | 0 |
So
. In C hexadecimal numbers are written with the prefix 0x. Memory addresses, web page colours (#FF8000) and register values in datasheets are written in hexadecimal.
Signed numbers: two’s complement
The natural way to represent negatives, a sign bit plus the magnitude, has two flaws: two zeros (+0 and −0) and different adder circuits for positives and negatives. Every processor uses two’s complement instead: with
bits, the most significant bit weighs
instead of
.

With 4 bits:
. The ranges are
to
: with 8 bits −128 to 127, with 32 bits about −2.1 to +2.1 billion.
How to change sign. Invert all the bits and add 1. From
: invert, 1010; add 1, 1011 = −5. Check:
, and the carry beyond the fourth bit is discarded: 0.
The advantage. Addition works the same way for positives and negatives: the same adder computes
by adding
, that is 4 discarding the carry. Subtraction becomes addition of the opposite.
Overflow
If the result does not fit in the available bits, it “wraps round” the wheel. With 8-bit signed numbers,
. In C:
#include <stdio.h>
#include <stdint.h>
int main(void)
{
uint8_t u = 250;
u = u + 10; /* unsigned: 260 - 256 = 4 */
printf("%u\n", u); /* prints 4 */
int16_t t = 30000;
t = t + 10000; /* signed: the result does not fit in 16 bits */
printf("%d\n", t); /* on almost every system prints -25536 */
return 0;
}For unsigned types C guarantees arithmetic modulo
. For signed ones overflow is undefined behaviour: the compiler may assume it never happens, and results can be surprising. It is one of the most common sources of firmware bugs: a 32-bit unsigned millisecond counter wraps to zero after about 49.7 days, and code comparing times must allow for it.
The fixed-width types of <stdint.h> (uint8_t, int16_t, uint32_t, …) are preferred in microcontroller programs, because the size of int changes from one processor to another: 16 bits on an AVR, 32 on an ARM.
Real numbers
Numbers with a fractional part are represented in floating point according to IEEE 754 (the float and double types in C), described in the Numerical Analysis lesson on errors. On microcontrollers without a floating-point unit fixed point is often used instead: you work with integers that represent, for example, thousandths (a voltage of 3.301 V becomes 3301 mV).
Characters
A character is a number according to an encoding table. ASCII (1963) uses 7 bits for 128 characters: ‘A’ = 65, ‘a’ = 97, ‘0’ = 48, space = 32, newline = 10. In C a char is a small integer, and you can do arithmetic on characters: '7' - '0' is 7, the standard way to turn a digit into a number.
For all the world’s scripts there is Unicode, with over 150,000 characters, almost always encoded in UTF-8: ASCII characters take one byte, accented letters two (è = 0xC3 0xA8), ideograms three, emoji four. That is why a C string holding “café” takes 5 bytes, not 4.
Bitwise operators
C lets you work on individual bits with the operators & (AND), | (OR), ^ (XOR), ~ (NOT), << and >> (shifts). A left shift by
positions multiplies by
: x << 3 equals x * 8. They are essential for communication protocols and for peripheral registers, as we will see in the lesson on C for embedded systems.
3Algorithms and complexity
An algorithm is a finite sequence of unambiguous instructions that solves a problem. The word comes from the name of the Persian mathematician al-Khwarizmi, and the first algorithm we know of, Euclid’s for the greatest common divisor, is more than two thousand years old. Before writing code it pays to design the algorithm: that is where you decide whether the program will be correct and fast. In this lesson we see how an algorithm is described, the basic structures of structured programming and how cost, that is complexity, is measured.
Properties of an algorithm
- Finiteness: it ends after a finite number of steps.
- Unambiguity: each step has a single meaning.
- Input and output: it receives data and produces a result.
- Effectiveness: each step can really be carried out with the available operations.
- Generality: it solves a class of problems, not a single case.
How to describe it: flowcharts and pseudocode
A flowchart represents the algorithm with blocks joined by arrows: ovals for start and end, parallelograms for input and output, rectangles for operations, diamonds for decisions.

Pseudocode describes the same algorithm in a language halfway between English and a programming language, more compact than the flowchart:
read a, b
while b ≠ 0:
r ← a mod b
a ← b
b ← r
write aWhy it works. Every common divisor of
and
also divides
, and vice versa: so
. Since
, the second number shrinks at each step and reaches 0 in finitely many steps, and
.
Structured programming
The Böhm-Jacopini theorem (1966, two Italian computer scientists) proves that any algorithm can be written using only three structures:
- sequence: one instruction after another;
- selection: if a condition is true do one thing, otherwise another (
if); - iteration: repeat while a condition is true (
while).
Arbitrary jumps (goto), which make code hard to follow, are not needed: this is the basis of structured programming, and of the C we will see from the next lesson.
Complexity
Two correct algorithms for the same problem can take very different times. Computational complexity measures how the number of operations grows as the size
of the data grows. The
notation is used: an algorithm is
if for large
it performs at most a number of operations proportional to
.
| Complexity | Example | ||
|---|---|---|---|
| accessing an array element | 1 | 1 | |
| binary search in a sorted array | 10 | 20 | |
| finding the maximum of an array | |||
| merge sort, FFT | |||
| bubble sort, direct DFT | |||
| trying every subset | impossible |
At a billion operations per second,
operations take a quarter of an hour;
take two hundredths of a second. Improving the algorithm matters far more than buying a faster computer.
Example: how many steps Euclid takes. Every two steps the first number at least halves (it is easy to prove), so the number of steps is at most about
of the smaller number:
. For 300-digit numbers, like those of RSA cryptography, a few thousand steps are enough, a fraction of a millisecond. Trying every divisor would be impossible.
Linear search and binary search
Searching for a value in an array of
unsorted elements means looking at them one by one:
. If the array is sorted you can do much better: look at the middle element, and depending on whether it is larger or smaller than the value sought, discard half the array. After
steps
elements remain, so
steps are enough: 20 comparisons for a million elements, 30 for a billion.
/* returns the index of x in the sorted array v of n elements, or -1 */
int binary_search(const int v[], int n, int x)
{
int lo = 0, hi = n - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2; /* avoids computing lo + hi, which could overflow */
if (v[mid] == x) return mid;
if (v[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Computing mid as lo + (hi - lo) / 2 instead of (lo + hi) / 2 is not pedantry: with indices close to the largest value of an int, the sum would overflow. It is a bug that stayed for years in the standard libraries of several languages.
4The C language: types, operators, input and output
C, created by Dennis Ritchie at Bell Labs between 1969 and 1973 to write the Unix operating system, is still the language of operating systems, drivers, firmware and almost every microcontroller. It is small, fast and close to the hardware, and for exactly that reason it demands discipline: the compiler checks little and leaves memory in the programmer’s hands. In this lesson we write the first programs: structure, types, variables, operators, input and output.
The first program
#include <stdio.h>
int main(void)
{
printf("Hello, world!\n");
return 0;
}#include <stdio.h>asks the preprocessor to include the declarations of the standard input/output library, whereprintflives.mainis the function where execution starts. It returns anint: 0 tells the operating system that all went well.- Braces delimit a block; each statement ends with a semicolon.
\nin the string is the newline character.
Compile and run with gcc hello.c -o hello and ./hello. Always turn on warnings, gcc -Wall -Wextra: many C errors are reported only as warnings.

Types and variables
Every variable has a type, which sets how many bytes it takes and how its bits are interpreted, and must be declared before use.
| Type | Typical size | Content |
|---|---|---|
char | 1 byte | character or small integer |
int | 4 bytes (2 on some microcontrollers) | signed integer |
long long | 8 bytes | large signed integer |
float | 4 bytes | floating point, about 7 digits |
double | 8 bytes | floating point, about 16 digits |
unsigned gives the unsigned versions. sizeof(type) tells how many bytes a type takes on that system.
int n = 10; /* declaration with initialisation */
double v = 3.3;
char c = 'A'; /* in single quotes: a character, that is the number 65 */
const double PI = 3.14159265358979; /* constant: cannot be modified */Careful: an uninitialised local variable holds a random value, whatever was in that memory before. Using it before assigning a value is an error the compiler does not always report.
Operators
- Arithmetic:
+ - * /and%(remainder). Between integers division truncates:7 / 2is 3,7 % 2is 1. To get 3.5 at least one operand must be real:7.0 / 2. - Assignment:
=, and the shorthand forms+=,-=,*=;i++increasesiby one. - Comparison:
== != < > <= >=. They give 1 (true) or 0 (false): C has no built-in boolean type, and any non-zero value is true (with<stdbool.h>you can usebool,trueandfalse). - Logical:
&&(and),||(or),!(not). They “short-circuit”: inb != 0 && a / b > 2the division is not performed ifbis zero.
The classic mistake is writing if (x = 5) instead of if (x == 5): the first assigns 5 to x and the condition is always true. With -Wall the compiler warns.
Conversions. In an expression with different types, the “smaller” type is converted to the “larger” one: in n * 2.5 the integer n becomes a double. Assigning a real to an integer drops the fractional part: int k = 3.9; is 3. You can convert explicitly with a cast: (double)sum / n.
Input and output
printf prints with a format, in which % specifiers mark where and how to insert values: %d integer, %u unsigned, %f real, %c character, %s string, %x hexadecimal. %.2f prints two decimals, %5d takes at least five characters.
scanf reads from the keyboard with the same format, but it needs the variable’s address, obtained with & (we will see why in the lesson on pointers):
#include <stdio.h>
int main(void)
{
double r1, r2;
printf("Values of the two resistors in ohms: ");
if (scanf("%lf %lf", &r1, &r2) != 2) { /* scanf returns how many values it read */
printf("Invalid input\n");
return 1;
}
double series = r1 + r2;
double parallel = r1 * r2 / (r1 + r2);
printf("Series: %.1f ohm, parallel: %.1f ohm\n", series, parallel);
return 0;
}With 1000 and 2200 the program prints “Series: 3200.0 ohm, parallel: 687.5 ohm”. Note %lf to read a double with scanf, while printf needs only %f, and the check on the value scanf returns: a robust program never trusts its input.
Style matters
A program is written once and read many times, often by someone else. Variable names that say what they hold (voltage_mV rather than x), consistent indentation, comments that explain why and not what, short functions. The compiler ignores all this; whoever has to fix a bug at two in the morning does not.
5Control structures
A program that always executes the same statements in the same order is of little use. Control structures let you choose what to do depending on the data and repeat operations. They are the three structures of structured programming (sequence, selection, iteration) translated into C. In this lesson we cover if, switch, while, do-while and for, with typical examples and the most frequent mistakes.
Selection: if and else
if (temperature > 85) {
fan_speed = 100;
printf("Alarm: high temperature\n");
} else if (temperature > 60) {
fan_speed = 70;
} else {
fan_speed = 30;
}The condition is an expression: if it is zero it is false, otherwise true. Braces can be omitted if the branch holds a single statement, but it is a dangerous habit: adding a second indented line makes it look part of the branch while it actually always runs. In 2014 a mistake of this kind (a duplicated goto fail; line) disabled SSL certificate verification in Apple’s systems.
The conditional operator. To choose a value compactly: maximum = (a > b) ? a : b;.
Multiple selection: switch
When choosing among many cases based on the integer value of an expression:
switch (command) {
case 'A':
led_on();
break;
case 'S':
led_off();
break;
case 'L':
case 'l': /* two cases sharing the same code */
led_blink();
break;
default:
printf("Unknown command: %c\n", command);
}break leaves the switch. If it is missing, execution “falls through” into the next case: sometimes intended, as for ‘L’ and ‘l’, more often a bug. switch is the natural structure for state machines, used everywhere in firmware: a communication protocol, a device menu, a motor start-up sequence.
The while loop
It repeats a block while the condition is true; the condition is checked before each iteration, so the block may never run.
/* how many digits a positive integer has */
int n = 40527, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
/* digits is 5 */
The do-while loop
Like while, but the condition is checked after: the block runs at least once. It suits cases where something must be done before deciding whether to repeat it, such as asking for input until it is valid:
int choice;
do {
printf("Choose a value between 1 and 5: ");
scanf("%d", &choice);
} while (choice < 1 || choice > 5);The for loop
It is the compact form for counter loops: initialisation, condition and update sit on one line.
/* average of n samples */
double sum = 0.0;
for (int i = 0; i < n; i++) {
sum += samples[i];
}
double average = sum / n;It is equivalent to a while with the initialisation before and the update at the end of the block. In C indices start at 0: an array of n elements goes from 0 to n - 1, so the condition is i < n, not i <= n. Being off by one is the most common bug of all.
Nested loops. For example the times table:
for (int r = 1; r <= 10; r++) {
for (int c = 1; c <= 10; c++) {
printf("%4d", r * c);
}
printf("\n");
}The inner block runs
times. With two nested loops over
elements the cost is
: the reason bubble sort is slow.
break and continue
breakleaves the innermost loop at once;continueskips the rest of the current iteration and moves to the next.
/* find the first sample above threshold, ignoring invalid (negative) ones */
int found = -1;
for (int i = 0; i < n; i++) {
if (samples[i] < 0) continue;
if (samples[i] > threshold) { found = i; break; }
}The microcontroller’s endless loop
A microcontroller program never ends: after initialisation it enters an infinite loop that reads inputs, updates the state and drives outputs.
int main(void)
{
init_peripherals();
for (;;) { /* or while (1) */
read_sensors();
update_state();
update_outputs();
}
}It is the structure Arduino hides behind its setup() and loop() functions.
Frequent mistakes
- A semicolon after the condition:
while (i < n);is an empty loop, infinite ifidoes not change. - Comparing reals with
==: after floating-point calculations0.1 * 3 == 0.3is false. Use a tolerance. - Changing a
forcounter inside the loop: it works, but it makes the code hard to follow. - Forgetting to update the condition variable in a
while: an infinite loop.
6Functions and recursion
A long program written entirely in main soon becomes unreadable. Functions let you split the problem into parts, each with a name, parameters and a result, to be written, tested and reused separately. In this lesson we see how they are defined, how parameters are passed, what happens in memory during a call (the stack) and recursion.
Definition and call
#include <stdio.h>
/* prototype: tells the compiler the name, parameters and result type */
double divider(double vin, double r1, double r2);
int main(void)
{
double vout = divider(12.0, 10e3, 4.7e3);
printf("Vout = %.2f V\n", vout); /* Vout = 3.84 V */
return 0;
}
/* output voltage of a resistive divider */
double divider(double vin, double r1, double r2)
{
return vin * r2 / (r1 + r2);
}- The prototype before
mainlets you use the function before defining it. Prototypes are usually collected in a.hheader file. - The formal parameters (
vin,r1,r2) are local variables that receive the values of the arguments passed in the call. returnends the function and returns the value. A function that returns nothing has typevoid.
Pass by value
In C arguments are passed by value: the function gets a copy, and changing it does not change the caller’s variable.
void twice(int x) { x = 2 * x; } /* changes only the local copy */
int main(void)
{
int n = 5;
twice(n);
printf("%d\n", n); /* prints 5, not 10 */
return 0;
}To let a function change a caller’s variable, or return more than one result, you pass its address: the subject of the lesson on pointers, and the reason scanf wants &n.
Scope and lifetime of variables
- Local variables, declared inside a function or block, exist only while that block runs and are visible only there.
- Global variables, declared outside every function, exist for the whole program and are visible everywhere. Convenient but dangerous: any function can change them, and finding who did is hard.
- A
staticlocal variable keeps its value between calls: useful for a counter internal to a function.
The call stack
Each function call creates in memory an activation record (stack frame) holding the parameters, the local variables and the return address. Records pile up on the stack: the one on top is the running function; on return it is removed and execution resumes in the caller.
That is why local variables “vanish” at the end of the function: their space is reused by the next call. Returning the address of a local variable is one of the most serious mistakes in C.
Recursion
A recursive function calls itself on a smaller problem. It needs two ingredients: a base case solved directly and a recursive step that shrinks the problem towards the base case.
unsigned long fact(unsigned int n)
{
if (n <= 1) return 1; /* base case */
return n * fact(n - 1); /* recursive step */
}
Recursion is natural for problems that contain smaller copies of themselves: tree structures, “divide and conquer” algorithms such as merge sort and the FFT, exploring a maze.
The costs. Each call takes stack space. With too deep a recursion the stack runs out (stack overflow) and the program crashes: a real risk on microcontrollers, where the stack is a few kilobytes. Some recursions also repeat a lot of work: Fibonacci written as fib(n) = fib(n-1) + fib(n-2) recomputes the same values an exponential number of times; fib(40) needs over 300 million calls. The loop version needs 40 steps.
unsigned long fib(unsigned int n)
{
unsigned long a = 0, b = 1;
for (unsigned int i = 0; i < n; i++) {
unsigned long t = a + b;
a = b;
b = t;
}
return a;
}Designing with functions
A good function does one thing, has a name that describes it, few parameters and no hidden side effects. It can be checked on its own, with a small test program that calls it with values whose result is known: the idea behind unit tests. The C standard library (<math.h>, <string.h>, <stdlib.h>) is an example of small, reusable functions: before writing one, check whether it already exists.
7Arrays and strings
Almost every program works on many data of the same type: the samples of a signal, a class’s marks, the pixels of an image, the characters of a message. The array is the structure that holds them in consecutive memory cells, reached by an index. In this lesson we cover one- and multi-dimensional arrays, how to pass them to functions, character strings and the dangers of going out of bounds.
Arrays
#define N 5
int marks[N] = {28, 30, 24, 27, 30}; /* N consecutive integers in memory */
int sum = 0;
for (int i = 0; i < N; i++) {
sum += marks[i];
}
printf("Average: %.2f\n", (double)sum / N); /* Average: 27.80 */- The size must be known and does not change: an array cannot grow (that is what the dynamic memory of the lesson on pointers is for).
- Indices run from 0 to
N - 1. - The elements sit in contiguous cells: the address of
marks[i]is that ofmarks[0]plusitimes the size of anint. That is why reaching any element takes the same time,
. - Using a constant (
#define N 5) instead of repeating the number 5 everywhere avoids forgetting one when the size changes.
Going out of bounds
C does not check that the index is valid. Writing marks[5] in an array of 5 elements gives no error: it reads or writes the next cell, which belongs to another variable. The result is unpredictable behaviour, which may show up much later in a distant part of the program. It is the cause of buffer overflows, the most exploited security vulnerability in history: an attacker writes past the end of an array and overwrites the return address on the stack, getting their own code executed. The 1988 Morris worm and countless later attacks used exactly this.
The rules of defence: always keep the size next to the array, check indices that come from outside, compile during development with -fsanitize=address, which reports out-of-bounds accesses.
Arrays and functions
An array passed to a function is not copied: the function receives the address of the first element. That is why it must also receive the size, and why it can change the caller’s array.
/* returns the index of the largest value */
int index_of_max(const int v[], int n)
{
int imax = 0;
for (int i = 1; i < n; i++) {
if (v[i] > v[imax]) imax = i;
}
return imax;
}const declares that the function does not change the array: the compiler checks it, and anyone reading the prototype knows at once.
Matrices
A two-dimensional array is an array of rows, stored one after another (row-major order):
double m[3][4]; /* 3 rows, 4 columns */
m[1][2] = 5.0; /* row 1, column 2 */
/* matrix-vector product: y = A x */
void mat_vec(int r, int c, const double a[r][c], const double x[c], double y[r])
{
for (int i = 0; i < r; i++) {
y[i] = 0.0;
for (int j = 0; j < c; j++) {
y[i] += a[i][j] * x[j];
}
}
}Walking a matrix row by row (with the column index in the inner loop) is much faster than walking it by columns, because contiguous cells are read and the cache works well: with large matrices the difference can be tenfold.
Strings
In C a string is an array of char ended by the null character '\0' (the number 0). The string "ciao" takes 5 bytes: ‘c’, ‘i’, ‘a’, ‘o’, ‘\0’. The terminator is how functions know where the string ends.
#include <stdio.h>
#include <string.h>
int main(void)
{
char name[20] = "Ada"; /* room for 19 characters plus the terminator */
printf("%s has %zu letters\n", name, strlen(name)); /* Ada has 3 letters */
char greeting[40];
snprintf(greeting, sizeof greeting, "Hello, %s!", name); /* never beyond the size */
printf("%s\n", greeting);
if (strcmp(name, "Ada") == 0) { /* strings are compared with strcmp, not == */
printf("Same name\n");
}
return 0;
}The functions of <string.h> (strlen, strcpy, strcat, strcmp) all rely on the terminator. If it is missing, or the destination is too small, the array bounds are exceeded: strcpy and gets are the historic causes of many buffer overflows. The versions that take the size, such as snprintf, should be preferred. == between two strings compares addresses, not content: for content you need strcmp, which returns 0 if they are equal.

An electronics example: the moving average
To smooth a sensor reading you average the last
samples, kept in an array used as a circular buffer: the new sample replaces the oldest, and the index wraps to 0 after the last cell.
#define N 8
static int buffer[N];
static int pos = 0;
static long sum = 0;
int moving_average(int sample)
{
sum -= buffer[pos]; /* remove the oldest sample */
buffer[pos] = sample;
sum += sample;
pos = (pos + 1) % N; /* circular index */
return (int)(sum / N);
}Keeping the sum up to date, each new sample costs a few operations whatever
is:
instead of
. It is a low-pass FIR filter, like those of the lesson on the Z transform.
8Pointers and dynamic memory
Pointers are C’s most powerful feature and the one that scares learners most. The idea is actually simple: a pointer is a variable that holds a memory address. With pointers a function can change the caller’s variables, arrays are walked through, memory is allocated at run time and hardware registers are accessed directly. In this lesson we take them step by step, together with dynamic memory and the mistakes to avoid.
Addresses and pointers
Each variable occupies one or more memory cells, and the & operator gives its address. A pointer is declared with an asterisk and holds an address; the * operator applied to the pointer gives access to the variable pointed to (dereferencing).
int x = 42;
int *p = &x; /* p holds the address of x: p "points to" x */
printf("%d\n", *p); /* 42: the value of the variable pointed to */
*p = 7; /* changes x through the pointer */
printf("%d\n", x); /* 7 */The pointer’s type (int *, double *, char *) says what kind of data is at the address, and therefore how many bytes to read. The null pointer NULL points to nothing: it is the value used to say “no object”, and dereferencing it crashes the program.
Pass by reference
To let a function change a caller’s variable, pass it the variable’s address:
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
int main(void)
{
int x = 3, y = 8;
swap(&x, &y); /* now x is 8 and y is 3 */
return 0;
}This way a function can also return several results, for example the magnitude and phase of a complex number, and it is why scanf wants &x: it must write into the caller’s variable.
Pointers and arrays
An array’s name, in almost every expression, converts to the address of its first element. And you can do arithmetic on pointers: p + 1 is not the next byte address, but that of the next element.

The equivalences a[i] == *(a + i) and &a[i] == a + i hold. You can walk an array with a pointer:
double average(const double *v, int n)
{
double s = 0.0;
for (const double *p = v; p < v + n; p++) {
s += *p;
}
return s / n;
}Dynamic memory
Arrays have a fixed size, decided when the program is written. If the size is known only at run time (how many samples to read from a file, how many nodes a circuit has) you ask the system for memory with malloc, in the area called the heap, and give it back with free when it is no longer needed.
#include <stdlib.h>
int n = read_sample_count();
double *samples = malloc(n * sizeof *samples);
if (samples == NULL) { /* malloc can fail: always check */
fprintf(stderr, "Out of memory\n");
return 1;
}
/* ... use samples[0] ... samples[n - 1] like an array ... */
free(samples);
samples = NULL; /* avoids reusing it by mistake */The classic mistakes
- Uninitialised pointer:
int *p; *p = 5;writes to a random address. - Dereferencing NULL: for example not checking the result of
malloc. - Memory leak: forgetting
free. In a program that runs for months, such as a router’s firmware, memory runs out little by little. - Use after free: using memory after freeing it. Its content may have been reassigned to something else.
- Double free: freeing the same block twice corrupts the allocator’s internal structures.
- Pointer to a local variable returned from a function: when the function ends, the variable no longer exists.
These mistakes account for a large share of the vulnerabilities in software written in C and C++: that is why newer languages such as Rust check memory use at compile time. Tools such as valgrind and AddressSanitizer find them during testing.
On microcontrollers dynamic allocation is almost always avoided: with a few kilobytes of RAM, repeated allocations and frees fragment the memory until malloc fails after hours or days of operation. Guidelines for critical software, such as MISRA C used in automotive, forbid it after initialisation: static arrays sized for the worst case are used instead.
Function pointers
A pointer can also hold the address of a function, which is then called through it. It is used to choose behaviour at run time: the standard library’s qsort receives a pointer to the function that compares two elements, and microcontrollers’ interrupt vector tables are arrays of pointers to the functions to run when an interrupt arrives.
9Structs and data structures
An array holds data of the same type. But often a piece of information is made of different data that belong together: a component has a code, a value, a tolerance and a stock quantity. C’s structs group fields of different types into a single new type. With structs and pointers you build dynamic data structures, the first of which is the linked list. In this lesson we see both, with their pros and cons compared with arrays.
Structs
#include <stdio.h>
struct component {
char code[16];
double value; /* in ohms, farads or henries */
double tolerance; /* in per cent */
int quantity;
};
int main(void)
{
struct component r = {"R-10K", 10e3, 1.0, 250};
r.quantity -= 10; /* fields are accessed with a dot */
printf("%s: %.0f ohm +/- %.0f%%, %d pieces\n", r.code, r.value, r.tolerance, r.quantity);
return 0;
}With typedef the type gets a shorter name: typedef struct component Component;. Structs can be copied by assignment, passed to functions and put in arrays: Component stock[500]; is a small database.
A large struct passed by value is copied in full. Usually its address is passed instead, and fields are accessed with the arrow operator: p->value is shorthand for (*p).value.
double minimum_value(const Component *c)
{
return c->value * (1.0 - c->tolerance / 100.0);
}The linked list
An array has two limits: its size is fixed, and inserting an element in the middle means shifting all the ones after it,
. A linked list solves both: each element (node) holds the data and a pointer to the next node; the last one points to NULL.
typedef struct node {
int value;
struct node *next;
} Node;
Inserting and traversing
#include <stdlib.h>
/* inserts v after node prev; returns the new node or NULL */
Node *insert_after(Node *prev, int v)
{
Node *n = malloc(sizeof *n);
if (n == NULL) return NULL;
n->value = v;
n->next = prev->next; /* 1: the new node points to the next one */
prev->next = n; /* 2: the previous one points to the new node */
return n;
}
void print(const Node *head)
{
for (const Node *p = head; p != NULL; p = p->next) {
printf("%d ", p->value);
}
printf("\n");
}The order of the two assignments matters: doing them the other way round loses the reference to the rest of the list. Removing a node is just as quick: the previous one is made to point to the next, and the removed node is released with free.
Array or list?
| Operation | Array | Linked list |
|---|---|---|
| access to the i-th element | ||
| insert or remove in the middle (position known) | ||
| growth | fixed size or reallocation | one node at a time |
| extra memory | none | one pointer per node |
| cache use | excellent, contiguous cells | poor, scattered nodes |
In practice, on modern processors, arrays are often faster even when theory favours lists, precisely because of the cache. Lists are useful when insertions and removals at known positions are frequent, or when elements must stay at the same address.
Stacks, queues and other structures
Arrays and lists are used to build the fundamental data structures:
- stack: the last item in is the first out (LIFO). It is the function call stack, and the one used by a reverse Polish notation calculator.
- queue: the first item in is the first out (FIFO). It is the circular buffer receiving the bytes of a serial port: the receive interrupt puts them in the queue, the main program reads them at its own pace.
- trees: each node has several successors. Binary search trees find an element in
steps, and file systems organise folders and files as a tree. - hash tables: they find an element from its key in average time
, computing the position directly with a function of the key. They are Python’s “dictionaries” and JavaScript’s objects.
Choosing the right data structure is half the work of designing a program: as Niklaus Wirth put it, algorithms plus data structures equal programs.
10Sorting algorithms
Sorting data is one of the most frequent operations: a ranking, a list of components by price, samples for computing the median, data before a binary search. And it is the ground on which the importance of an algorithm’s complexity shows best: with a million elements, a good algorithm takes a tenth of a second, a naive one hours. In this lesson we cover the elementary sorts, merge sort and quicksort, and the theoretical limit that cannot be beaten.
Bubble sort and insertion sort
Bubble sort: walk the array swapping adjacent pairs that are out of order; after each pass the largest element has reached the end, like a rising bubble. Up to
passes of
comparisons are needed:
.
Insertion sort: build the sorted part one element at a time, inserting each new element in its place among those already sorted, the way you arrange playing cards in your hand.
void insertion_sort(int v[], int n)
{
for (int i = 1; i < n; i++) {
int x = v[i];
int j = i - 1;
while (j >= 0 && v[j] > x) { /* shift the larger ones right */
v[j + 1] = v[j];
j--;
}
v[j + 1] = x;
}
}This too is
in the worst case, but on nearly sorted data it is very fast, almost
, and with few elements (up to a few dozen) it beats the more sophisticated algorithms. That is why libraries use it for small pieces.
Merge sort: divide and conquer
The idea is recursive:
- split the array into two halves;
- sort each half (recursively);
- merge the two sorted halves into a single sorted sequence.

Merging two sorted sequences is easy: compare their first elements and take the smaller, until one of them runs out.
#include <string.h>
/* merges v[lo..mid-1] and v[mid..hi-1], already sorted, using tmp as scratch space */
static void merge(int v[], int tmp[], int lo, int mid, int hi)
{
int i = lo, j = mid, k = lo;
while (i < mid && j < hi) tmp[k++] = (v[i] <= v[j]) ? v[i++] : v[j++];
while (i < mid) tmp[k++] = v[i++];
while (j < hi) tmp[k++] = v[j++];
memcpy(v + lo, tmp + lo, (hi - lo) * sizeof v[0]);
}
void merge_sort(int v[], int tmp[], int lo, int hi) /* sorts v[lo..hi-1] */
{
if (hi - lo < 2) return;
int mid = lo + (hi - lo) / 2;
merge_sort(v, tmp, lo, mid);
merge_sort(v, tmp, mid, hi);
merge(v, tmp, lo, mid, hi);
}Why it costs 
At each level of the recursion the merges handle all
elements in total, and there are
levels, because the parts halve at each level. So the total work is proportional to
. With
: about
operations against bubble sort’s
. Merge sort is also stable (equal elements keep their original order), but it needs a scratch array as large as the one being sorted.
Quicksort
Choose an element, the pivot, and rearrange the array so the smaller elements are on the left and the larger on the right; then sort the two parts recursively. It needs no extra memory and, on average, it is the fastest in practice,
. But if the pivot is always the smallest or largest (for example taking the first element of an already sorted array), the parts are unbalanced and the cost becomes
. Serious implementations choose the pivot at random or as the median of three elements. The C standard library’s qsort often uses it, with a pointer to the comparison function:
#include <stdlib.h>
static int compare(const void *a, const void *b)
{
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y); /* -1, 0, 1 with no risk of overflow */
}
/* ... */
qsort(v, n, sizeof v[0], compare);The theoretical limit
An algorithm that sorts only by comparing pairs of elements must tell apart all
possible permutations, and each comparison has two outcomes: at least
comparisons are needed in the worst case. By Stirling’s formula
. So no comparison sort can do better than
: merge sort is optimal.
The limit can be beaten only by exploiting the structure of the data. Counting sort sorts
integers between 0 and
by counting how often each value appears, in
: the fastest way to build the histogram and the median of a 12-bit converter’s readings (
).
Which to choose
| Algorithm | Average case | Worst case | Extra memory | Stable |
|---|---|---|---|---|
| insertion | yes | |||
| merge sort | yes | |||
| quicksort | no | |||
| heapsort | no |
In practice the library function is almost always used. On a microcontroller, with few elements and little memory, insertion sort is often the best choice: simple, with no recursion and no extra memory.
11C for microcontrollers
For an electronics engineer C is not just for calculations: it is for making a microcontroller work, that is switching on an LED, reading a button, generating a PWM signal, talking to a sensor. This kind of programming, in direct contact with the hardware, is called embedded. In this lesson we put together what we have seen (fixed-width types, bitwise operators, pointers, loops) to understand how C controls peripherals through registers, and we look at interrupts and the rules of robust firmware.
Peripheral registers
In a microcontroller each peripheral (input/output ports, timers, analogue-to-digital converter, serial interfaces) is controlled by writing and reading its registers: memory cells at fixed addresses, described in the datasheet, in which each bit or group of bits has a meaning. For example, in an 8-bit output port, writing 1 to bit 3 drives pin 3 high.

Bit operations
To change one bit without touching the others you use masks: (1u << n) is a number with only bit n set.
#include <stdint.h>
#define LED_PIN 3
PORTB |= (1u << LED_PIN); /* set bit 3: LED on */
PORTB &= ~(1u << LED_PIN); /* clear bit 3: LED off */
PORTB ^= (1u << LED_PIN); /* toggle bit 3: the LED changes state */
if (PINB & (1u << 2)) { /* read bit 2: button pressed? */
/* ... */
}For multi-bit fields, mask and shift are used together. If bits 4 to 6 of a configuration register select an interface’s speed (8 possible values):
reg = (reg & ~(0x7u << 4)) | ((speed & 0x7u) << 4); /* writes 3 bits leaving the others alone */
uint8_t s = (reg >> 4) & 0x7u; /* reads them back */This is exactly what manufacturers’ library functions (HAL) do, and it pays to be able to read them anyway: when something does not work, you go and look at the register.
How a register is accessed: volatile
Registers sit at fixed addresses. In manufacturers’ header files they are defined more or less like this:
#define GPIOA_ODR (*(volatile uint32_t *)0x40020014u)
GPIOA_ODR |= (1u << 5); /* writes directly to address 0x40020014 */The address is converted to a pointer and dereferenced. The volatile keyword tells the compiler that the value can change at any moment for reasons outside the program (the hardware, or an interrupt) and that every read and write must really be performed, in the order written. Without volatile an optimising compiler might read a register only once and reuse the value, or remove a write that “looks” useless: the code works without optimisation and breaks with -O2, one of the classic mysteries for beginners.
Interrupts
Checking a button continuously in a loop (polling) wastes time and can miss short events. With interrupts the hardware tells the processor: when an event arrives (an edge on a pin, a byte on the serial port, a timer expiring) the processor suspends what it is doing, runs a dedicated function, the interrupt service routine (ISR), and then resumes.
#include <stdint.h>
#include <stdbool.h>
volatile bool data_ready = false; /* shared between ISR and main: volatile */
volatile uint16_t last_reading;
void ADC_IRQHandler(void) /* called by the hardware at end of conversion */
{
last_reading = ADC_DATA; /* the converter's register */
data_ready = true;
}
int main(void)
{
init_adc();
for (;;) {
if (data_ready) {
data_ready = false;
process(last_reading);
}
/* here the processor can also be put in low-power mode until the next interrupt */
}
}The rules for ISRs: they must be short (no printf, no waiting), variables shared with the main program must be declared volatile, and if they are wider than the processor reads in one go (a uint32_t on an 8-bit processor) access from the main program must be protected by briefly disabling interrupts, otherwise you can read a value that is half old and half new.
Timing without blocking
A delay(500) function blocks the processor for half a second: during that time it does not read buttons or answer the serial port. Well-written firmware uses a millisecond counter updated by a timer and compares times:
static uint32_t last = 0;
if ((uint32_t)(millis() - last) >= 500u) { /* unsigned subtraction survives the wrap-around */
last += 500u;
blink_led();
}Thanks to unsigned integers’ modulo
arithmetic (lesson on data representation), the difference is correct even when the counter restarts from zero after 49.7 days.
The rules of robust firmware
- Use fixed-width types (
uint8_t,int32_t) and check overflow edge cases. - Avoid
mallocafter initialisation and deep recursion: memory is scarce and an error does not show up at once. - Enable the watchdog, a hardware timer that resets the microcontroller if the program hangs and stops “feeding” it.
- Always read the component’s datasheet and errata: peripherals have precise initialisation sequences and, sometimes, documented defects.
- Compile with all warnings, and in professional projects follow a standard such as MISRA C.
This is where the course ends: from computer architecture to a microcontroller’s registers, C remains the language through which software talks directly to electronics.