MIPS system calls — exercises with a potion shop, a friend code with its check digit and a guild register (and the menu that brought out the final boss with a 7)
The week before the lab exam I did a mock run with a classmate: each of us wrote a program and the other tried to break it from the keyboard. Mine was a three-option difficulty menu with its table of addresses, as clean as could be. My classmate typed a 7. The console said: «Mode: Slime King». The final boss of easy mode had sneaked in as a difficulty level. I hadn’t validated the option, and lw had happily read the word six positions past the start of the table.
That sums up the topic better than any definition: the user can type anything, and your program has to be ready for it. In these exercises you read numbers, texts and digits, store them where they belong and check that they make sense before using them. If you’re coming from the system calls practice, you’ve already seen the sheet, the menu and the points; here it’s your turn to write the code.
Table of Contents
How to use this article
- Read the task and the expected output for each level. The inputs that appear in the output are what the user types.
- Write your program in Notepad++ (or in the web playground) and test it in QtSpim with those same inputs and with others that try to break it.
- If you get stuck, open the hint. Don’t look at the solution until your program works or you’ve been at it for a good while.
- Before the solutions come the three «What’s wrong here?» snippets: predict the output before reading the explanation.
Level 1 · Basic: the potion shop
The player walks into the shop. The program asks how many gold coins they have, the price of a potion and how many they want. It works out the total and, if they can afford it, says how many coins they have left; if not, how many they’re short. The three numbers have to be kept in $s registers as soon as they arrive.
Expected output with 250 coins, potions at 35 and 4 potions:
Gold coins: 250 Price of a potion: 35 How many do you want: 4 Total: 140 Purchase done. You have 110 coins.
And with 100 coins:
Gold coins: 100 Price of a potion: 35 How many do you want: 4 Total: 140 Not enough: you're short 40 coins.
Three read_int, each with its move $sN, $v0 underneath. The total is mul. To know which message to print, a bgt between the total and the gold; the figure printed afterwards is a subtraction one way or the other, and you can leave it in $a0 before jumping to a shared print_int.
Level 2 · Intermediate: the friend code
To add someone as a friend, the game asks for their 12-digit code. The program reads it as text and checks that there are exactly 12 characters and that all of them are digits; if not, it says so and asks again. The digits are stored as numbers (0 to 9) in a 12-byte array. Then it checks the check digit: the last digit must equal the sum of the first 11 modulo 10. Finally, it prints the code in groups of 4 separated by a space and says whether the check digit is correct (or which digit it should end in).
Expected output (the user gets it wrong twice: first typing the spaces and then leaving out a digit):
Friend code (12 digits): 3141 5926 5354 Invalid code: it must be 12 digits in a row. Friend code (12 digits): 31415926535 Invalid code: it must be 12 digits in a row. Friend code (12 digits): 314159265354 Code: 3141 5926 5354 Check digit correct.
read_string into a 20-byte buffer, and a loop over the buffer with the index in $t0 that exits on the \n (or the 0). On each pass: is it a digit? (blt/bgt with '0' and '9'), do I already have 12?, subtract 48 and sb into dig($t0). When it exits, if $t0 isn’t 12, invalid. For the modulo, div and mfhi. For the groups: a space before digit i when i isn’t 0 and i % 4 == 0 (which is andi i, 3 equal to 0).
Level 3 · Challenge: the guild register
The guild takes at most 4 members. Each member is stored in a 16-byte record inside guild: .space 64: the first 12 bytes are the nick (at most 11 letters and its '\0') and the last 4, a word with the level. The program asks for nick and level, asks whether there’s another member (1 yes, 0 no) and stops when told no or when the guild is full. At the end it lists the members with the nick padded with spaces to 12 columns, so the levels line up, and the average level (integer division).
Expected output:
Nick: Kira Level: 19 Another member? (1 = yes, 0 = no): 1 Nick: Bram Level: 7 Another member? (1 = yes, 0 = no): 1 Nick: Lunaria Level: 12 Another member? (1 = yes, 0 = no): 0 Guild members: 1. Kira level 19 2. Bram level 7 3. Lunaria level 12 Average level: 12
Record n starts at guild + n · 16, and n · 16 is sll $s1, $s0, 4. Read the nick straight into the record (la $a0, guild($s1), $a1 = 12) and remove its \n right there. The level goes at guild+12($s1). For the padding, count the nick’s letters with a loop up to the '\0' and print 12 − letters spaces with print_char.
What’s wrong here?
Three snippets with a typical mistake of the topic. All of them assemble and run without complaining. Read each one, look at the input and predict the output before carrying on.
Snippet 1
The user types 30 and 45:
# Snippet 1: the gold in two chests
.data
p1: .asciiz "Gold in chest 1: "
p2: .asciiz "Gold in chest 2: "
tot: .asciiz "Total gold: "
.text
.globl main
main: la $a0, p1
li $v0, 4
syscall
li $v0, 5 # read_int: chest 1
syscall
la $a0, p2
li $v0, 4
syscall
move $t0, $v0 # save chest 1
li $v0, 5 # read_int: chest 2
syscall
add $t1, $t0, $v0 # total
la $a0, tot
li $v0, 4
syscall
move $a0, $t1
li $v0, 1
syscall
li $v0, 10
syscall
How much total gold comes out?
Gold in chest 1: 30 Gold in chest 2: 45 Total gold: 49
49. Not 75, not 30 + 30. The move $t0, $v0 is written correctly, but it arrives too late: between chest 1’s read_int and the move there’s a print_string for the second message, and that li $v0, 4 leaves a 4 in $v0. The «chest 1» that gets saved is a 4, and 4 + 45 = 49.
Thinking the move is fine anywhere «before the next read». No: it has to go before the next syscall, whatever kind it is. Printing a message is a syscall too.
Fixed, with the move right next to its syscall:
# Snippet 1 fixed: the move right after the syscall
.data
p1: .asciiz "Gold in chest 1: "
p2: .asciiz "Gold in chest 2: "
tot: .asciiz "Total gold: "
.text
.globl main
main: la $a0, p1
li $v0, 4
syscall
li $v0, 5 # read_int: chest 1
syscall
move $t0, $v0 # save chest 1 BEFORE another syscall
la $a0, p2
li $v0, 4
syscall
li $v0, 5 # read_int: chest 2
syscall
add $t1, $t0, $v0 # total
la $a0, tot
li $v0, 4
syscall
move $a0, $t1
li $v0, 1
syscall
li $v0, 10
syscall
Gold in chest 1: 30 Gold in chest 2: 45 Total gold: 75
Snippet 2
The guild leader is called Kira. The program asks for the nick and compares it letter by letter. The user types exactly «Kira»:
# Snippet 2: look the player up by nickname
.data
buf: .space 16
leader: .asciiz "Kira" # the guild leader
pnick: .asciiz "Your nick: "
tyes: .asciiz "Welcome, leader.\n"
tno: .asciiz "You are not the leader.\n"
.text
.globl main
main: la $a0, pnick
li $v0, 4
syscall
la $a0, buf
li $a1, 16
li $v0, 8 # read_string
syscall
la $t0, buf # compare buf with leader, letter by letter
la $t1, leader
cmp: lbu $t2, 0($t0)
lbu $t3, 0($t1)
bne $t2, $t3, no # a different letter: it is not
beqz $t2, yes # both end at the same time: it is
addi $t0, $t0, 1
addi $t1, $t1, 1
j cmp
yes: la $a0, tyes
j done
no: la $a0, tno
done: li $v0, 4
syscall
li $v0, 10
syscall
Your nick: Kira You are not the leader.
«You are not the leader». The comparison goes fine for four letters: K, i, r, a. On the fifth, buf holds a 10 (the \n that read_string left) and leader holds a 0 (the end of "Kira"). They’re different, so it jumps to no. The loop is correct; the problem is that it compares «Kira + newline» with «Kira».
When two strings that «are the same» don’t come out equal, print what was read between brackets ([Kira and ] on the next line gives it away) or look at the buffer in the Data tab for an 0a.
Fixed, removing the \n before comparing:
# Snippet 2 fixed: remove the '\n' first
.data
buf: .space 16
leader: .asciiz "Kira" # the guild leader
pnick: .asciiz "Your nick: "
tyes: .asciiz "Welcome, leader.\n"
tno: .asciiz "You are not the leader.\n"
.text
.globl main
main: la $a0, pnick
li $v0, 4
syscall
la $a0, buf
li $a1, 16
li $v0, 8 # read_string
syscall
la $t0, buf # remove the '\n' from what was read
q: lbu $t2, 0($t0)
beq $t2, '\n', nul
beqz $t2, trimmed
addi $t0, $t0, 1
j q
nul: sb $zero, 0($t0)
trimmed: la $t0, buf # compare buf with leader, letter by letter
la $t1, leader
cmp: lbu $t2, 0($t0)
lbu $t3, 0($t1)
bne $t2, $t3, no # a different letter: it is not
beqz $t2, yes # both end at the same time: it is
addi $t0, $t0, 1
addi $t1, $t1, 1
j cmp
yes: la $a0, tyes
j done
no: la $a0, tno
done: li $v0, 4
syscall
li $v0, 10
syscall
Your nick: Kira Welcome, leader.
Snippet 3
This is my menu from the mock run. The user types 7:
# Snippet 3: the difficulty menu
.data
modes: .word mf, mn, md # name of each mode
lives: .word 5, 3, 1 # lives you start with
bosses: .word j1, j2, j3 # the final boss of each mode
mf: .asciiz "Easy"
mn: .asciiz "Normal"
md: .asciiz "Hard"
j1: .asciiz "Slime King"
j2: .asciiz "Iron Golem"
j3: .asciiz "Ash Dragon"
pmod: .asciiz "Difficulty (1-3): "
tmode: .asciiz "Mode: "
.text
.globl main
main: la $a0, pmod
li $v0, 4
syscall
li $v0, 5 # read_int
syscall
addi $t0, $v0, -1 # index from 0
sll $t0, $t0, 2 # each address, 4 bytes
lw $s0, modes($t0) # address of the mode name
la $a0, tmode
li $v0, 4
syscall
move $a0, $s0
li $v0, 4
syscall
li $v0, 10
syscall
Difficulty (1-3): 7 Mode: Slime King
«Mode: Slime King». With a 7, the offset is (7 − 1) · 4 = 24. The modes table only has 12 bytes (+0, +4, +8); at +24 bosses begins, and its first word is the address of «Slime King». lw doesn’t know where your table ends: it loads whatever word is there and print_string prints whatever it finds at that address.
With a 4, a 5 or a 6 it’s worse: the word loaded is one of the lives (5, 3 or 1), print_string gets an impossible address and the program ends with a memory error. And with a 0, it reads the word before the table.
Trusting the user to type what the message says. «Difficulty (1-3)» is a request, not a guarantee. Any option used as an index is checked first.
Fixed, validating and asking again (the user types 7 and then 3):
# Snippet 3 fixed: validate before using the index
.data
modes: .word mf, mn, md # name of each mode
lives: .word 5, 3, 1 # lives you start with
bosses: .word j1, j2, j3 # the final boss of each mode
mf: .asciiz "Easy"
mn: .asciiz "Normal"
md: .asciiz "Hard"
j1: .asciiz "Slime King"
j2: .asciiz "Iron Golem"
j3: .asciiz "Ash Dragon"
pmod: .asciiz "Difficulty (1-3): "
tmode: .asciiz "Mode: "
.text
.globl main
main: la $a0, pmod
li $v0, 4
syscall
li $v0, 5 # read_int
syscall
blt $v0, 1, main # outside 1..3: ask again
bgt $v0, 3, main
addi $t0, $v0, -1 # index from 0
sll $t0, $t0, 2 # each address, 4 bytes
lw $s0, modes($t0) # address of the mode name
la $a0, tmode
li $v0, 4
syscall
move $a0, $s0
li $v0, 4
syscall
li $v0, 10
syscall
Difficulty (1-3): 7 Difficulty (1-3): 3 Mode: Hard
Solutions
Level 1 solution
Before the code, the plan. Three numbers arrive one after another, and between every two reads there’s a print_string that leaves a 4 in $v0. So each number needs its own $s register as soon as it arrives:
| Data | Register | Why $v0 isn’t enough |
|---|---|---|
| gold | $s0 | it’s compared at the end, five syscalls later |
| price | $s1 | «How many do you want: » is printed before the mul |
| quantity | $s2 | there’s no syscall before the mul here, but this way the rule is the same for all three |
Why bgt and a subtraction in each branch, and not the path that looks shorter, a single subtraction gold − total and checking the sign: it would work, but with 100 coins it gives −40 and you’d have to flip it to write «you’re short 40». By comparing first, each branch subtracts in the direction that leaves the number positive.
# level1.s: the potion shop (level 1 solution)
.data
pgold: .asciiz "Gold coins: "
pprice: .asciiz "Price of a potion: "
pqty: .asciiz "How many do you want: "
ttot: .asciiz "Total: "
tleft: .asciiz "\nPurchase done. You have "
tshort: .asciiz "\nNot enough: you're short "
tcoins: .asciiz " coins.\n"
.text
.globl main
main: la $a0, pgold
li $v0, 4
syscall
li $v0, 5 # read_int: gold
syscall
move $s0, $v0 # $s0 = gold (out of $v0 straight away)
la $a0, pprice
li $v0, 4
syscall
li $v0, 5 # read_int: price
syscall
move $s1, $v0 # $s1 = price
la $a0, pqty
li $v0, 4
syscall
li $v0, 5 # read_int: quantity
syscall
move $s2, $v0 # $s2 = quantity
mul $s3, $s1, $s2 # total = price * quantity
la $a0, ttot
li $v0, 4
syscall
move $a0, $s3
li $v0, 1
syscall
bgt $s3, $s0, short # total > gold: not enough
la $a0, tleft
li $v0, 4
syscall
sub $a0, $s0, $s3 # what is left over
j digit
short: la $a0, tshort
li $v0, 4
syscall
sub $a0, $s3, $s0 # what is missing (positive)
digit: li $v0, 1 # $a0 already holds the number
syscall
la $a0, tcoins
li $v0, 4
syscall
li $v0, 10
syscall
Why it’s done this way:
- A
moveunder eachread_int. The three reads have aprint_stringin between: without themoves, the gold and the price would be lost as in snippet 1. mul $s3, $s1, $s2: 35 · 4 = 140. In both cases the total is the same; what changes is the gold.- The subtraction both ways. With 250, 250 − 140 = 110 are left. With 100, they’re 140 − 100 = 40 short: the total minus the gold, so that it comes out positive («you’re short 40», not «you’re short −40»).
- A single
print_intat the end (digit). Each branch leaves its number in$a0and jumps to the same place. You could duplicate theprint_intin both branches, but this way there’s one exit.
bgt $s3, $s0, short uses «greater than»: if the total is exactly equal to the gold, they can afford it and have 0 left. With bge it would tell them they’re 0 coins short, which is odd.
Writing the comparison the wrong way round, bgt $s0, $s3, short. The branches cross over and so do the subtractions: with 250 coins the program says Not enough: you're short -110 coins. and with 100, Purchase done. You have -40 coins. If a figure that should be positive comes out negative, first check the order of the registers in the branch.
Level 2 solution
The plan, before the code: a friend code isn’t a number, it’s a row of 12 digits. It’s never added up or multiplied as a whole; everything the task asks for is done by looking at one digit at a time. That’s why the program splits into three phases, each with its own loop over the same index $t0:
- Read and check. Walk the text character by character up to the
\n, and on the way turn each character into its digit. - The check digit. Add up the first 11 digits and keep the remainder after dividing by 10.
- Print. Walk the 12 digits again, with a space before each group of 4.
Why the digits are copied into dig as numbers instead of working straight on buf: in buf the character '3' is worth 51, not 3. Subtracting 48 just once, while reading, means the other two phases already work with real digits: the sum comes out right and print_int writes each digit as it is.
# level2.s: the 12-digit friend code (level 2 solution)
.data
buf: .space 20 # typed text (plenty for 12 + '\n')
dig: .byte 0:12 # the 12 digits, already as numbers
pcode: .asciiz "Friend code (12 digits): "
tbad: .asciiz "Invalid code: it must be 12 digits in a row.\n"
tcode: .asciiz "Code: "
tok: .asciiz "\nCheck digit correct.\n"
tko: .asciiz "\nCheck digit wrong: it should end in "
.text
.globl main
main: # --- 1. read and check: 12 digits and nothing else ---
read: la $a0, pcode
li $v0, 4
syscall
la $a0, buf
li $a1, 20
li $v0, 8 # read_string
syscall
li $t0, 0 # i = 0 (valid characters)
digit: lbu $t1, buf($t0) # c = buf[i]
beq $t1, '\n', done # end of what was typed
beqz $t1, done
blt $t1, '0', bad # a character that is not a digit
bgt $t1, '9', bad
beq $t0, 12, bad # already had 12: too many digits
addi $t1, $t1, -48 # character -> number
sb $t1, dig($t0) # dig[i] = digit
addi $t0, $t0, 1
j digit
done: bne $t0, 12, bad # fewer than 12: also wrong
# --- 2. check digit: sum of the first 11, modulo 10 ---
li $t0, 0
li $s0, 0 # sum = 0
sum: beq $t0, 11, rest
lb $t1, dig($t0)
add $s0, $s0, $t1
addi $t0, $t0, 1
j sum
rest: li $t2, 10
div $s0, $t2 # LO = quotient, HI = remainder
mfhi $s1 # $s1 = sum % 10, the expected check digit
# --- 3. print in groups of 4 ---
la $a0, tcode
li $v0, 4
syscall
li $t0, 0
group: beq $t0, 12, ctrl
beqz $t0, one # no space before the first one
andi $t3, $t0, 3 # i % 4 == 0 -> a group starts
bnez $t3, one
li $a0, ' '
li $v0, 11
syscall
one: lb $a0, dig($t0) # the digit as a number...
li $v0, 1 # ...and print_int writes it
syscall
addi $t0, $t0, 1
j group
ctrl: lb $t1, dig+11 # the last digit
beq $t1, $s1, good
la $a0, tko
li $v0, 4
syscall
move $a0, $s1
li $v0, 1
syscall
li $a0, '\n'
li $v0, 11
syscall
j quit
good: la $a0, tok
li $v0, 4
syscall
quit: li $v0, 10
syscall
bad: la $a0, tbad
li $v0, 4
syscall
j read
The reading and checking loop, up close:
li $t0, 0 # i = 0 (valid characters)
digit: lbu $t1, buf($t0) # c = buf[i]
beq $t1, '\n', done # end of what was typed
beqz $t1, done
blt $t1, '0', bad # a character that is not a digit
bgt $t1, '9', bad
beq $t0, 12, bad # already had 12: too many digits
addi $t1, $t1, -48 # character -> number
sb $t1, dig($t0) # dig[i] = digit
addi $t0, $t0, 1
j digit
done: bne $t0, 12, bad # fewer than 12: also wrong
Why it’s done this way:
- The index
$t0does two jobs: it walks the buffer (buf($t0)) and writes into the array (dig($t0)). Both are made of bytes, so nosllis needed. - Three ways to reach
bad: a character that isn’t a digit, a 13th digit (beq $t0, 12, badbefore storing it, so as not to write outsidedig) and fewer than 12 at the end (bne $t0, 12, bad). - Why it’s read as text and not with
read_int: 314159265354 doesn’t fit in 32 bits (the maximum is 2147483647) and, besides,read_intwould keep «3141» on seeing the space in the first attempt, without telling you. div+mfhi:divleaves the quotient in LO and the remainder in HI. Sum of the first 11: 3 + 1 + 4 + 1 + 5 + 9 + 2 + 6 + 5 + 3 + 5 = 44, and 44 mod 10 = 4, which is the last digit. Check digit correct.- The groups:
andi $t3, $t0, 3isi % 4(the two low bits). A space is printed before digit 4 and digit 8; not before digit 0, because of thebeqz.
| Attempt | What was typed | Where it stops | Result |
|---|---|---|---|
| 1 | 3141 5926 5354 | At character 4, the space (32 < 48) | Invalid |
| 2 | 31415926535 | On reaching the \n with $t0 = 11 | Invalid |
| 3 | 314159265354 | On reaching the \n with $t0 = 12 | Valid |
What if the user types 13 digits?
With 3141592653541 the first 12 are stored. The final 1 arrives with $t0 already at 12: it’s a digit, but beq $t0, 12, bad jumps before the sb, so it’s rejected without writing anything outside dig.
Removing beq $t0, 12, bad because «the bne $t0, 12, bad at the end is already there». The 13-digit code is still invalid, but first the sb has written digit 13 into dig+12, which is the first byte of pcode, right after it in .data. The «F» becomes a byte worth 1 that you can’t see: the next prompt comes out as riend code (12 digits):.
Forgetting the addi $t1, $t1, -48. dig ends up holding characters: the sum is 44 + 11 · 48 = 572, the check digit comes out as 2 and it prints Code: 51495249 53575054 53515352 followed by Check digit wrong: it should end in 2.
Level 3 solution
The plan starts by drawing one record: 16 bytes, the first 12 for the nick and the last 4 for the level. With that, every piece of data has an address that comes from a single sum:
| Member | n | $s1 = n · 16 | Nick at | Level at |
|---|---|---|---|---|
| Kira | 0 | 0 | guild+0 | guild+12 |
| Bram | 1 | 16 | guild+16 | guild+28 |
| Lunaria | 2 | 32 | guild+32 | guild+44 |
| (fourth) | 3 | 48 | guild+48 | guild+60 |
Why records and not the path that looks easier, two separate arrays (one of 12-byte nicks and another of 4-byte levels): each member would need two offsets, n · 12 and n · 4, and n · 12 can’t be done with an sll. With the record there’s only one, $s1, and the nick and the level are at +0 and +12.
# level3.s: the guild register with 16-byte records (level 3 solution)
.data
guild: .space 64 # 4 records x 16 bytes: nick (12) + level (4)
pnick: .asciiz "Nick: "
plev: .asciiz "Level: "
pmore: .asciiz "Another member? (1 = yes, 0 = no): "
tfull: .asciiz "The guild is full.\n"
thead: .asciiz "\nGuild members:\n"
tdot: .asciiz ". "
tlev: .asciiz "level "
tavg: .asciiz "Average level: "
.text
.globl main
main: li $s0, 0 # n = registered members
enrol: sll $s1, $s0, 4 # $s1 = n * 16: start of record n
la $a0, pnick
li $v0, 4
syscall
la $a0, guild($s1) # the nick goes at the start of the record
li $a1, 12 # at most 11 letters + '\0'
li $v0, 8 # read_string
syscall
move $t0, $a0 # remove the '\n' INSIDE the record
q: lbu $t1, 0($t0)
beq $t1, '\n', nul
beqz $t1, level
addi $t0, $t0, 1
j q
nul: sb $zero, 0($t0)
level: la $a0, plev
li $v0, 4
syscall
li $v0, 5 # read_int
syscall
sw $v0, guild+12($s1) # level at byte 12 of the record
addi $s0, $s0, 1 # one more member
beq $s0, 4, full # no more records fit
la $a0, pmore
li $v0, 4
syscall
li $v0, 5
syscall
bnez $v0, enrol # 1 (or any non-zero): another one
j listing
full: la $a0, tfull
li $v0, 4
syscall
listing: la $a0, thead
li $v0, 4
syscall
li $t5, 0 # i = 0
li $s2, 0 # sum of levels
row: beq $t5, $s0, average
addi $a0, $t5, 1 # member number, from 1
li $v0, 1
syscall
la $a0, tdot
li $v0, 4
syscall
sll $s1, $t5, 4 # start of record i
la $a0, guild($s1)
li $v0, 4 # the nick
syscall
la $t0, guild($s1) # how many letters does the nick have?
li $t2, 0
count: lbu $t1, 0($t0)
beqz $t1, pad
addi $t2, $t2, 1
addi $t0, $t0, 1
j count
pad: li $t3, 12 # pad up to 12 columns with spaces
sub $t3, $t3, $t2
spc: blez $t3, lv
li $a0, ' '
li $v0, 11
syscall
addi $t3, $t3, -1
j spc
lv: la $a0, tlev
li $v0, 4
syscall
lw $a0, guild+12($s1)
add $s2, $s2, $a0 # sum += level
li $v0, 1
syscall
li $a0, '\n'
li $v0, 11
syscall
addi $t5, $t5, 1
j row
average: la $a0, tavg
li $v0, 4
syscall
div $s2, $s0 # sum / n (integer division)
mflo $a0
li $v0, 1
syscall
li $v0, 10
syscall
Why it’s done this way:
sll $s1, $s0, 4turns the member number into the offset of their record: 0, 16, 32, 48. It’s topic 4’s index with a 16-byte «element».- The nick is read straight into the record.
la $a0, guild($s1)gives the address of the start of the record and$a1 = 12stopsread_stringwriting beyond the nick (at most 11 letters +'\0'), so it never touches the level. move $t0, $a0after thesyscall.read_stringdoesn’t change$a0, so the nick’s address is still there: it’s the starting point of the loop that removes the\n.sw $v0, guild+12($s1): the level goes 12 bytes after the start of the record. Since 16 and 12 are multiples of 4, the word stays aligned.- Two exits from the sign-up loop:
beq $s0, 4, fullbefore asking (if no more fit, it doesn’t even ask) andbnez $v0, enrolafterwards (any number other than 0 counts as yes). - The padding: «Kira» has 4 letters, so 12 − 4 = 8 spaces are printed and «level» starts after 15 characters (3 for «1. » + 12). «Lunaria» has 7: 5 spaces.
- The average: (19 + 7 + 12) / 3 = 38 / 3 = 12 with
divandmflo(integer division: the remainder, 2, is lost).
Reading the nick with $a1 = 16 «because the record is 16 bytes». A 15-letter nick would also take up the level’s 4 bytes, and the later sw would overwrite its last letters. The size in $a1 is the field’s, not the record’s.
Not removing the \n from the nick «because it’s only going to be printed». It gets printed with its newline, and it also counts as one more letter when working out the padding: «Kira» gives 5, so 7 spaces go in, and on the next line.
1. Kira
level 19
2. Bram
level 7
3. Lunaria
level 12
What if four sign up?
After the fourth level, $s0 is 4 and beq $s0, 4, full jumps before asking: it prints The guild is full. and goes on to the list. With a fourth member at level 30, the average is 68 / 4 = 17.
Practice quiz
Twelve questions on the whole topic: the syscall sequence, the services, read_int and $v0, read_string and its \n, read_char, reading into an array, from text to number and menus with a table of addresses. It doesn’t count for anything: it’s there to show you what you’re clear on and what you’re not, so you can repeat it as often as you like. Every answer comes with its explanation.
Before running syscall, which register holds the service code (1, 4, 5, 8…)?
- $v0
- $a0
- $a1
- $t0
Solution
Answer: $v0
The sequence is always the same: arguments in $a0 (and $a1), code in $v0 and syscall. If the service returns something, it lands in $v0 (or in the buffer).
Match each service with the code that goes in $v0:
| print_int | |
| print_string | |
| read_int | |
| read_string | |
| print_char |
Definitions:
- 2
- 1
- 4
- 11
- 36
- 5
- 8
Solution
- print_int → 1
- print_string → 4
- read_int → 5
- read_string → 8
- print_char → 11
2 is print_float (floating point, outside this topic) and 36 does not exist in SPIM or QtSpim: it belongs to another simulator, MARS.
The user types 30. What does this snippet print?
li $v0, 5 # read_int syscall li $v0, 1 # print_int move $a0, $v0 syscall
- 1
- 30
- 5
- 0
Solution
Answer: 1
What read_int returns lives in $v0 until you change it. Here li $v0, 1 changes it before it is copied: you need move $a0, $v0 first (or better, move it to an $s register right after the syscall).
With name: .space 10, $a1 = 10 and read_string, say whether each statement is true or false:
- If you type Kira, the buffer holds K, i, r, a, the newline and a ‘\0’.
- $a1 is the maximum number of letters stored.
- If you type 12 letters, 9 are stored and there is no newline.
- read_string leaves in $v0 how many characters it read.
Solution
- T — If you type Kira, the buffer holds K, i, r, a, the newline and a ‘\0’.
- F — $a1 is the maximum number of letters stored.
- T — If you type 12 letters, 9 are stored and there is no newline.
- F — read_string leaves in $v0 how many characters it read.
read_string stores at most $a1 − 1 characters (it leaves room for the ‘\0’), puts the ‘\n’ in only if it fits and returns nothing in $v0: you count the length yourself.
nam is a .space 8 and the user types Ana. What appears on the console after what was typed?
la $a0, open # "[" li $v0, 4 syscall la $a0, nam # what read_string left li $v0, 4 syscall la $a0, close # "]" li $v0, 4 syscall
- [Ana] on a single line
- [Ana on one line and ] on the next
- [Ana\n] with the backslash and the n visible
- Nothing, because the buffer is too small
Solution
Answer: [Ana on one line and ] on the next
It’s the most typical mistake of the topic: the newline is inside the string and shows up where you least expect it. You fix it by finding the ‘\n’ and doing sb $zero on top of it.
Complete how to remove the newline from a buffer:
I walk through the buffer with ____ until I find code ____ and write a zero on top with sb ____. If I find a 0 first, the text filled the buffer and there is no newline to remove.
Words:
- 32
- 10
- $zero
- $v0
- lw
- lbu
Solution
I walk through the buffer with lbu until I find code 10 and write a zero on top with sb $zero. If I find a 0 first, the text filled the buffer and there is no newline to remove.
The ‘\n’ is character 10. It is read byte by byte (lbu) and replaced with a 0 (sb $zero), which becomes the end of the string.
In QtSpim, a program does two read_char in a row. You press K and, out of habit, Enter. What does the second read_char return?
- 10
- It waits for you to press another key
- 75
- 0
Solution
Answer: 10
In QtSpim read_char takes the key as soon as you press it, without waiting for Enter. If you press Enter, that ‘\n’ is another character and the next read takes it. In the web playground you always send a line with its Enter, so it always happens.
Put the steps in order to read an integer without losing it:
- Copy the result from $v0 to another register or to memory
- Now another syscall is safe
- Put the service code in $v0
- Set up the arguments (if the service needs them)
- Run syscall
Solution
Correct order:
- Set up the arguments (if the service needs them)
- Put the service code in $v0
- Run syscall
- Copy the result from $v0 to another register or to memory
- Now another syscall is safe
Arguments, code, syscall and, if the service returns something, move it out of $v0 before the next call, because that call starts with li $v0.
txt is .asciiz "305". What number does this program print?
la $t0, txt
li $s0, 0
li $t3, 10
loop: lbu $t1, 0($t0)
beqz $t1, done
addi $t1, $t1, -48
mul $s0, $s0, $t3
add $s0, $s0, $t1
addi $t0, $t0, 1
j loop
done: addi $a0, $s0, 1
li $v0, 1
syscallSolution
Answer: 306
The loop turns the characters ‘3’, ‘0’, ‘5’ into the number 305 (0·10 + 3 = 3, 3·10 + 0 = 30, 30·10 + 5 = 305) and prints 305 + 1 = 306. Without subtracting 48, it would add up the ASCII codes.
You want to read 4 integers into v: .word 0:4 with the index in $t0. Which two lines go after each read_int?
- sll $t1, $t0, 2
- sw $v0, v($t1)
- sb $v0, v($t0)
- lw $v0, v($t1)
Solution
Answer: sll $t1, $t0, 2 · sw $v0, v($t1)
Offset = i · 4 with sll and sw of $v0 at that position. If the array were bytes (.byte), it would be sb $v0, v($t0), with no scaling.
With classes: .word cg, cm, ca, what does lw $a0, classes($t0) leave in $a0 when $t0 = 4?
- The address of the string cm
- The text of the string cm
- The first letter of cm
- The number 4
Solution
Answer: The address of the string cm
A table of addresses is an array of words whose elements are addresses. With the address in $a0, print_string prints the string.
In a 3-option menu with a table of addresses, the user types 7 and the program does not check it. What happens?
- lw reads whatever word is at table + 24
- SPIM warns that the index is outside the table
- Option 3, the last one, is printed
- read_int doesn’t let you type a 7
Solution
Answer: lw reads whatever word is at table + 24
You set the limits: check 1 ≤ option ≤ 3 (blt/bgt) before working out the offset and, if it is not valid, ask again.
Try it in QtSpim (or right here)
The friend code is the best one for trying to break from the keyboard. Open it in QtSpim or in the playground below:
Loading the MIPS playground… If it doesn’t appear, copy level2.s into your QtSpim.
- Try letters, 13 digits and an empty line: all three times it asks again.
- Type 314159265350 (last digit wrong): it tells you which digit it should end in.
- After a valid code, open the Data tab: in
dig(right behind the 20 bytes ofbuf) you see the twelve digits as bytes 03 01 04 01…, not as characters 33 31 34 31. - Set a breakpoint on
mfhi $s1and look at LO and HI in the registers: 4 and 4 with the good code (44 = 4 · 10 + 4). - Remove the line
beq $t0, 12, badand type 20 digits: what happens to whatever comes afterdigin the Data tab?
Cheat sheet: MIPS system calls
The essentials in 30 seconds
- Sequence: arguments in
$a0/$a1→li $v0, code→syscall→ collect the result. - Whatever a read returns comes out of
$v0before the next syscall (any syscall, printing ones included). read_stringkeeps the Enter inside the buffer if it fits: find it andsb $zeroon top.- What’s typed is checked before using it as an index, a digit or an amount.
QtSpim services
$v0 | Service | You give | You get back |
|---|---|---|---|
| 1 | print_int | $a0 = integer | — |
| 4 | print_string | $a0 = address of the string | — |
| 5 | read_int | — | integer in $v0 |
| 8 | read_string | $a0 = buffer, $a1 = size | text in the buffer (up to $a1 − 1 characters + \n if it fits + '\0') |
| 10 | exit | — | — |
| 11 | print_char | $a0 = character | — |
| 12 | read_char | — | character in $v0 |
36 (print unsigned) belongs to MARS: it doesn’t exist in QtSpim.
I want to…
| I want to… | Code | Result |
|---|---|---|
| Read an integer and not lose it | li $v0, 5 / syscall / move $s0, $v0 | The number in $s0 |
| Read an integer into memory | li $v0, 5 / syscall / sw $v0, value | The number in value |
| Read a text | la $a0, buf / li $a1, 16 / li $v0, 8 / syscall | The text in buf |
Remove the \n | lbu loop up to 10 (also exit on 0) and sb $zero, 0($t0) | Clean string |
| Print a stored number | lw $a0, value / li $v0, 1 / syscall | Its value (with la you’d get the address) |
| Ask y/n without trouble | read_string into a .space 8 and lbu $t0, ans | First letter in $t0 |
| Store the i-th number read | sll $t1, $t0, 2 / sw $v0, v($t1) | v[i] |
| Turn a character into a digit | addi $t1, $t1, -48 | '7' → 7 |
| Build up digits | mul $s0, $s0, $t3 (with $t3 = 10) / add $s0, $s0, $t1 | n = n · 10 + digit |
| Print the text of option k | validate, addi, sll, lw $a0, table($t0), li $v0, 4 | String k |
| Line up columns | \t in the strings or pad with spaces (print_char) | Straight columns |
Templates
Removing the newline from a buffer:
la $t0, buf # pointer to the text read
q: lbu $t1, 0($t0)
beq $t1, '\n', nul # found: it becomes '\0'
beqz $t1, ready # no newline: the text filled the buffer
addi $t0, $t0, 1
j q
nul: sb $zero, 0($t0)
ready:
Validated menu with a table of addresses:
menu: la $a0, pmenu # the menu text
li $v0, 4
syscall
li $v0, 5 # read_int
syscall
blt $v0, 1, menu # out of range: again
bgt $v0, 3, menu
addi $t0, $v0, -1 # index from 0
sll $t0, $t0, 2 # each address, 4 bytes
lw $a0, table($t0) # address of the chosen string
li $v0, 4
syscall
Exercise templates
| Exercise | Skeleton | With the article’s inputs |
|---|---|---|
| Level 1: shop | 3 × (read_int + move), mul, bgt total/gold, subtraction the right way round | 250, 35, 4 → total 140, 110 left; 100 → 40 short |
| Level 2: friend code | read_string, loop with validation + sb into dig, sum of 11, div/mfhi, groups with andi i, 3 | 314159265354 → 3141 5926 5354, check digit correct (44 mod 10 = 4) |
| Level 3: guild | sll n, 4 for the record, nick in guild($s1) with $a1 = 12, level in guild+12($s1), padding to 12 | Kira 19, Bram 7, Lunaria 12 → average 12 |
Mistakes that come up most
| Symptom | Likely cause |
|---|---|
| The number read shows as 1, 4, 5, 8 or 11 | A syscall overwrote $v0 before the move or the sw |
| A newline in the middle of a sentence or a blank line | The \n wasn’t removed from a text that was read |
| Two equal strings «aren’t equal» | One of them has read_string‘s \n |
| Text cut short | .space or $a1 too small |
| A read doesn’t let you type | An Enter or leftover text from the previous read was still waiting |
| A menu prints another text or gives a memory error | Unvalidated option used as an index |
| The converted number is huge or absurd | The 48 wasn’t subtracted or '0'..'9' wasn’t checked |
| 268500… comes out instead of the data | la instead of lw before print_int |
Before you hand it in, ask yourself
- Does every reading
syscallhave itsmoveor itsswright underneath? - Have I removed the
\nfrom every text read withread_string? (The exam cheat sheet asks exactly that.) - Does
$a1match the.spaceof each buffer? - Do I check the range of everything I use as an index, digit or amount, and ask again if it’s not valid?
Did this article help you? Here is how you can support SergioLearns →
Ready for the exam?IC1 practical mock exam — MIPS in QtSpim with other data, subroutines and keyboard input (and why part 1 decides almost everything)


