```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
# Procedures
### Compile a Simple Leaf Procedure
```python
def func(x,y):
return x + y
```
---
```mips
func: add $v0, $a0, $a1
jr $ra
```
* the first argument to the procedure is in `$a0`
* the second argument to the procedure is in `$a1`
* the return value of the procedure goes in `$v0`
* `jr`: jump to the instruction whose address is in register `$ra`
```mips
func: add $v0, $a0, $a1
jr $ra
```
When you call this function, you must
* put the first argument in `$a0`
* put the second argument in `$a1`
* put the **return address** in `$ra`
* jump to the function
### Calling Our Leaf Procedure
```python
def func(x,y):
return x + y
def main():
func(1, 2)
```
---
```mips
func:
add $v0, $a0, $a1
jr $ra
main:
li $a0, 1 #load the first argument
li $a1, 2 #load the second argument
jal func
```
`jal`: **jump and link** - put the next instruction's address in `$ra` and jump to the procedure
### Nested Procedure Calls
```python
def main():
func(1, func(2, func(3, 4)))
```
---
```mips
main:
li $a0, 3
li $a1, 4
jal func
li $a0, 2
move $a1, $v0
jal func
li $a0, 1
move $a1, $v0
jal func
```
**remember:** `$v0` is where we find the returned value
## Calling a Procedure
1. Put parameters in appropriate registers
+
`$a0`, `$a1`, `$a2`, `$a3`
2.
Transfer control to the procedure: *jump and link*
+
`jal ProcedureLabel`
- puts the current instruction's address into `$ra`
3.
Perform task
4.
Place result in a location the callee can find
+
`$v0`, `$v1`
5.
Return control to the caller: *jump to addr. in register*
+
`jr $ra`
## Exercise
- Convert the following Python code into MIPS
- Make sure to create two functions
- make sure the print happens in `main`, not `double_it`
```python
def double_it(e):
return e + e
def main():
print( double_it(21) )
```