You are on page 1of 3

FACULTY OF INFORMATION TECHNOLOGY

DEPARTMENT OF COMPUTER NETWORK AND DATA COMMUNICATION


Subject: Computer organization

LAB 8
Procedures/Functions
1/ Procedure Format
Example:
Pascal:
proceduce <ProceduceName>(variables)
Begin
<Code here>;
End;

C: <ReturnType> function <functionName>(variables)


{
<Code here>;
}

Assembly:
.globl <ProcedureName>
.ent <ProcedureName>
ProcedureName:
<code here>
.end <ProcedureName>

Calling procedure should use the "jal <ProcedureName>" instruction (jal = jump and link)

The return from procedure is as follows: jr $ra #$ra contains the return address

Truong Dinh Tu 1
FACULTY OF INFORMATION TECHNOLOGY
DEPARTMENT OF COMPUTER NETWORK AND DATA COMMUNICATION
Subject: Computer organization

Example: Write a program to calculate the power (x^y), return the result to the
variable answer = power(x,y).

.data
x: .word 2
y: .word 3
answer: .word 0
.text
.globl main
main:
lw $a0, x
lw $a1, y

# call procedure
jal power
sw $v0,answer

# print answer
li $v0,1
lw $a0,answer
syscall

#thoát
li $v0,10
syscall
.end main

# procedure
.globl power
.ent power
power:
li $t0,0 # i=0
li $v0,1 # result = 1

powLoop:
mul $v0,$v0,$a0 # result = result * x
addi $t0,$t0,1 # i=i+1
blt $t0,$a1,powLoop # if i<y then powLoop
jr $ra # $ra contains the return address
.end power

Truong Dinh Tu 2
FACULTY OF INFORMATION TECHNOLOGY
DEPARTMENT OF COMPUTER NETWORK AND DATA COMMUNICATION
Subject: Computer organization

Exercises:
1/ Rewrite the program using a procedure to calculate the power x^y, with x, y input from
the keyboard
2/ Write a procedure to find the min or max of 2 numbers x, y (with x, y input from the
keyboard)
3/ Write a procedure to calculate N!
4/ Write a procedure to check the square of a number N.
5/ Write a procedure to check prime numbers.
6/ Write a procedure to check the perfect number.
7/ Write a procedure to find the greatest common divisor of 2 numbers a, b.

Truong Dinh Tu 3

You might also like