```mips
.data
i: 5
j: 8
k: 0
message: .asciiz "The value of k is "
.text
lw $s0, i
lw $s1, j
bne $s0, $s1, disp_msg
li $s2, 1
sw $s2, k
disp_msg:
li $v0, 4 #4 is the code for printing a string
la $a0, message #the argument for the syscall
syscall
li $v0, 1 #1 is the code for printing an int
lw $a0, k #the argument for the syscall
syscall
```
## Exercise
- Run the above program in Mars, observe the output
- Change it so `i` and `j` are equal, run again
- Translate the following Python program into MIPS
```python
if i == j:
k = 1
else:
k = 2
print("The value of k is",k)
```
## Compiling a `while` Statement
```python
i = 1
while i != 10:
print(i)
i += 1
```
---
```mips
.text
li $s0, 1
li $t0, 10
start_loop:
beq $s0, $t0, done
li $v0, 1 #print integer - no newline after!
add $a0, $s0, $zero #copy $s0 into $a0
syscall
addi $s0, $s0, 1
b start_loop
done:
```
## Exercise
- Translate this into MIPS
- Hint: can you use `slt` here?
```python
sum = 0
i = 0
while i < 10:
sum = sum + i
i += 1
print(sum)
```
## Assignment
- [Assignment 3](../../assignments/assignment-3/)
- Translate a Python program that has both an if statement and a loop
# Arrays
## What is an array?
An array is a series of data items stored in consecutive memory locations
- Python: list
- Java: array, ArrayList
- C/C++: array, Vector
## Example array program
```mips
.data
#arrays get stored in consecutive 32-bit memory addresses
my_array: 1, 2, 3, 4
.text
la $s0, my_array #load the base address of the array
#Addresses go up by 4 because each byte has its own address
#So a word takes up 4 addresses
lw $t0, 0($s0) #load my_array[0]
lw $t1, 4($s0) #load my_array[1]
lw $t0, 8($s0) #load my_array[2]
lw $t0, 12($s0) #load my_array[3]
```
### New flavor of `lw`
```mips
lw $t1, 4($s0) #load my_array[1]
```
- Meaning
- load the 32-bit value stored at the address `$s0`+4
- Good for accessing items in an array
- The other version: `la $t0, a`
- pseudoinstruction
## Arrays in memory
```mips
.data
#arrays get stored in consecutive 32-bit memory addresses
my_array: 1, 2, 3, 4
```

### Translating a program that uses an array
```python
my_array = [10,6,0,27,92,18,42]
i = 0
while i < 7:
print(my_array[i])
i = i + 1
```
```mips
.data
my_array: 10, 6, 0, 27, 92, 18, 42
newline: .asciiz "\n"
.text
la $s0, my_array #load the base address of the array
li $t0, 0 #loop counter
loop:
slti $t1, $t0, 7 #check if loop counter < 7
beq $t1, $zero, end #if not < 7, branch to end
#calculate address of next thing in the array
sll $t2, $t0, 2 #multiply the loop counter by 4
add $t2, $t2, $s0 #add counter*4 to my_array address
#print the item from the array
lw $a0, 0($t2) #load next value from array
li $v0, 1 #print integer
syscall
#print a newline
la $a0, newline
li $v0, 4 #print string
syscall
addi $t0, $t0, 1 #increment the loop counter
b loop
end:
```
## Exercise
- edit the above MIPS program to also find the sum of all the items in the array