Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Practice and Review

Practice Exercises with Solutions

Twenty graded assembly exercises on a runnable toy CPU: sums, gcd, fibonacci, popcount, array and string routines, with a checker and full solutions.

You learn assembly by writing it, and you only trust what you wrote after something checks it. This lesson gives you 20 exercises in three grades, a small checker that runs your program against several test inputs and reports PASS or FAIL, and a reference solution for every exercise. The solutions live in the editors below, so each exercise is a program you can run, edit, break and repair.

Everything runs on the toy CPU from Meet the Toy CPU: 32-bit registers rax, rbx, rcx, rdx, rsi, rdi and r8, the flags ZF, SF, CF and OF, a stack, and memory where each address holds one value. If a mnemonic here is unfamiliar, the lessons on arithmetic, logic and shifts, compare and jump, loops and strings cover each one.

How to work through them

Do not read the solution first. The method that works is the one real assembly programmers use:

  1. Say it in plain steps. "Start with sum = 0. Add n, then n - 1, down to 1." Pseudocode is allowed to be as short as three lines.
  2. Pick registers. Decide which register holds each variable and write it in a comment. Most bugs in assembly are two variables sharing a register.
  3. Write the loop skeleton (initialize, test, body, step, jump back) before the body.
  4. Test the edges: zero, one, the empty string, equal values, negative numbers. The checker below always includes some.
  5. Trace by hand one small input before you run it. When the output is wrong, run(program, { trace: ["rax", "rcx"] }) prints the registers and flags before every instruction.
flowchart LR
  A["Plain-language steps"] --> B["Assign registers<br/>to variables"]
  B --> C["Loop skeleton"]
  C --> D["Fill in the body"]
  D --> E["Run the checker"]
  E -->|"FAIL"| F["Trace one input<br/>by hand"]
  F --> D
  E -->|"PASS"| G["Try the edge cases<br/>you can think of"]

The loop that every exercise follows: plan, write, check, and trace whenever the checker fails.

How the checker works

Each exercise below is an object with a title, a program (src) and a list of tests. A test says which registers to preset (regs), which named arrays or strings to place in memory (data) and what the program must produce. Programs report numbers with out, and text with the toy syscall instruction (rax = 1 writes rdx characters starting at the address in rsi). For every exercise the checker runs all tests, compares the results and prints one line, with the number of instructions executed as a free performance measure.

Two conventions to know. A named array such as arr is available as the address arr and its length as arr_len; a string works the same way and ends with a 0 cell, which is how the string exercises find its end. And all numbers are 32-bit, so -1 and 0xFFFFFFFF are the same bits.

Grade 1: warm-ups (exercises 1 to 6)

# Task Input Expected output
1 Sum 1 + 2 + ... + n rcx = n (n at least 1) the sum: n = 10 gives 55
2 Largest element of an array array arr the maximum
3 Swap two registers without a third rax, rbx print rax, then rbx, swapped
4 Absolute value rax abs(rax)
5 Multiply rax by rcx using only addition rax, rcx the product
6 Parity: 1 if rax is even, otherwise 0 rax 1 or 0

For exercise 3, think about what xor does when applied twice. Exercise 5 is a good place to remember that the loop must handle rcx = 0.

JS Grade 1: sum, max, swap, abs, multiply, parity

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Want to practise instead of read? Replace the body of one src with your own attempt (or just delete it) and press Run: the checker tells you which test breaks and what your program printed.

Grade 2: loops and arrays (exercises 7 to 14)

# Task Input Expected output
7 Fibonacci number F(n), with F(0) = 0 and F(1) = 1 rcx = n F(n): n = 10 gives 55
8 Greatest common divisor (Euclid's algorithm) rax, rbx gcd
9 Factorial n! rcx = n n!: 6 gives 720
10 Count the 1 bits ("popcount") rax bit count
11 Sum of an array array arr the total
12 Reverse an array in place, then print it array arr the reversed elements
13 Minimum and maximum in one pass array arr print the minimum, then the maximum
14 Is rax a power of two? (1 or 0) rax 1 or 0

Euclid's algorithm repeats "replace (a, b) by (b, a mod b)" until b is zero, and div hands you the remainder in rdx. The popcount trick for exercise 14 uses the fact that n & (n - 1) clears the lowest set bit: a power of two has exactly one bit set, so the result is zero (but remember zero itself is not a power of two). The reversal in exercise 12 needs two indexes that walk toward each other.

JS Grade 2: fibonacci, gcd, factorial, popcount, arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how little the loop skeleton changes from exercise to exercise. Sum, factorial, Fibonacci and popcount all follow initialize, test, step, jump back; only the body differs.

Grade 3: strings and sorting (exercises 15 to 20)

# Task Input Expected output
15 Length of a string string text the length
16 Reverse a string in place and write it string word the reversed text
17 Convert lowercase letters to uppercase and write the result string msg the converted text
18 Parse a decimal string into a number (atoi) string digits the number
19 Palindrome check (1 or 0) string word 1 or 0
20 Bubble sort an array, then print it array arr the sorted elements

In these, characters are plain numbers: a is 97, z is 122, 0 is 48, and a lowercase letter becomes uppercase by subtracting 32. Each string ends with a 0, so "walk until you see 0" is the standard loop. Exercises 16 and 17 write their result with syscall, exactly as in Project: Hello World the Real Way.

JS Grade 3: strings, atoi, palindrome, bubble sort

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The bubble sort is the longest program of the set, and a good measure of progress: if you can read each of its three loops (outer pass, inner comparison, final print) and say which registers hold what, you can read most compiler output at the level of structure.

Where to go from here

When all 20 pass, change them. Make exercise 2 return the index of the maximum instead of the value. Write the opposite of exercise 17, uppercase to lowercase. Rewrite exercise 5 with shifts and adds so it takes about 32 steps even for huge multipliers. Port exercise 8 by hand to ARM64 using the ARM64 basics lesson, or build a bigger program in Project: Build Your Own Tiny CPU Emulator.

A failing check is information. Read the "expected, got" text first: an output that is off by one usually means a loop bound (jge versus jg), a swapped pair usually means a register reused too early, and a wrong sign means you used an unsigned jump (jb, ja) where you needed a signed one (jl, jg).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the Euclid GCD solution, why is xor rdx, rdx executed before every div rbx?

    div uses the register pair rdx:rax as the dividend and leaves the remainder in rdx. Stale data in rdx would change the dividend.
  2. 2. What is the cheapest way to test that a register holds zero?

    A value ANDed with itself is zero only when it is zero, and test keeps only the flags, so ZF tells you the answer without changing rax.
  3. 3. The expression n & (n - 1) is zero for which kind of n (excluding zero)?

    Subtracting 1 flips the lowest set bit and every bit below it, so the AND clears that lowest bit. The result is zero only if that was the only set bit.
  4. 4. Your minimum-and-maximum program gives the wrong answer for negative numbers. What is the most likely mistake?

    Unsigned conditions read -4 as 4,294,967,292, so it looks like a huge value. Signed numbers need the greater/less family.

Summary

  • Plan in plain steps, assign a register to every variable, write the loop skeleton, then fill in the body.
  • Always test edge cases: zero, one, empty input, equal values and negative numbers.
  • Loops over arrays and strings share one skeleton: initialize an index, test it, use [base + index], step, jump back.
  • Strings are walked until the 0 terminator; characters are numbers, so case conversion and atoi are plain arithmetic.
  • div needs rdx cleared first and hands you the remainder; n & (n - 1) clears the lowest set bit.
  • Choose jumps by signedness: jl/jg for signed, jb/ja for unsigned.

Next: see how the same ideas appear in interviews in Assembly Interview Questions.