CSCI-365 Computer Organization
CSCI-365 Computer Organization
Computer Organization
Lecture 4
Note: Some slides and/or pictures in the following are adapted from:
Computer Organization and Design, Patterson & Hennessy, ©2005
Some slides and/or pictures in the following are adapted from:
slides ©2008 UCB
Loops in C/Assembly
Solution
Similar to the “if-then” statement, but we need instructions for the
“else” part and a way of skipping the “else” part after the “then” part.
slt $t0,$s2,$s1 # j<i? (inverse condition)
bne $t0,$zero,else # if j<i goto else part
addi $t1,$t1,1 # begin then part: x = x+1
addi $t3,$zero,1 # z = 1
j endif # skip the else part
else: addi $t2,$t2,-1 # begin else part: y = y–1
add $t3,$t3,$t3 # z = z+z
endif:...
The For Example
addi $t0,$zero,0 # i = 0
loop1: sll $t1,$t0,2 # $t1 = i * 4
add $t2,$a0,$t1 # $t2 = &array[i]
sw $zero, 0($t2) # array[i] = 0
addi $t0,$t0,1 # i = i + 1
slt $t3,$t0,$a1 # $t3 = (i < size)
bne $t3,$zero,loop1 # if (…) goto loop1
Example: The C Switch Statement
switch (k) {
case 0: f=i+j; break; /* k=0 */
case 1: f=g+h; break; /* k=1 */
case 2: f=g–h; break; /* k=2 */
case 3: f=i–j; break; /* k=3 */
}
Example: The C Switch Statement
Solution
Scan the list, holding the largest element identified thus far in $t0.
# initialize maximum to A[0]
# initialize index i to 0
loop: # increment index i by 1
# if all elements examined, quit
# compute 2i in $t2
# compute 4i in $t2
# form address of A[i] in $t2
# load value of A[i] into $t3
# maximum < A[i]?
# if not, repeat with no change
# if so, A[i] is the new maximum
# change completed; now repeat
done: ... # continuation of the program
Finding the Maximum Value in a List of Integers
List A is stored in memory beginning at the address given in $s1.
List length is given in $s2.
Find the largest integer in the list and copy it into $t0.
Solution
Scan the list, holding the largest element identified thus far in $t0.
lw $t0,0($s1) # initialize maximum to A[0]
addi $t1,$zero,0 # initialize index i to 0
loop: add $t1,$t1,1 # increment index i by 1
beq $t1,$s2,done # if all elements examined, quit
add $t2,$t1,$t1 # compute 2i in $t2
add $t2,$t2,$t2 # compute 4i in $t2
add $t2,$t2,$s1 # form address of A[i] in $t2
lw $t3,0($t2) # load value of A[i] into $t3
slt $t4,$t0,$t3 # maximum < A[i]?
beq $t4,$zero,loop # if not, repeat with no change
addi $t0,$t3,0 # if so, A[i] is the new maximum
j loop # change completed; now repeat
done: ... # continuation of the program