Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

B. (10 pts) The function countChars(char str, char target) returns the number of

ID: 3910434 • Letter: B

Question

B. (10 pts) The function countChars(char str, char target) returns the number of times characters in target appear in str. For example: countChars("abc abc abc", "a")-3 countChars("abc abc abc", "ab") 6 countChars(abc abc abc", "abcd") 9 int countChars(char*str, char *target)f Int count 0; while ("str) count isCharlnStrtarget, "str); str++ The C code for countChars is given to you in the box on right. The helper function isCharinStr(char *target, char c) returns 1 if c is present in target and 0 if not. return count; Finish the implement of countChars in MIPS below countChars: addiu $sp, $sp, # Store onto the stack if needed addiu $s0, $zero, 0We'Il store the count in $so addiu $s1, $a0, o addiu $s2, $al, 0 loop: be jal isCharInStr done: # 1.cad from the stack if needed Name addiu $sp, sp r ra

Explanation / Answer

Below is the MIPS solution:

countChars:
     addiu $sp, $sp, -16
     sw $ra, 0($sp)           # Store onto the stack if needed
     sw $s0, 4($sp)
     sw $s1, 8($sp)
     sw $s2, 12($sp)
     addiu $s0, $zero, 0      # We'll store the count in $s0
     addiu $s1, $a0, 0
     addiu $s2, $a1, 0
loop:
     addiu $a0, $s2, 0
     lb $a1, 0($s1)
     beq $a1, $zero, done
     jal isCharInStr
     addu $s2, $s2, $v0
     addiu $s1, $s1, 1
     j loop
done:
     addiu $v0, $s2, 0        # Load from the stack if needed
     lw $ra, 0($sp)
     lw $s2, 4($sp)
     lw $s1, 8($sp)
     lw $s2, 12($sp)
     addiu $sp, $sp, 16
     jr $ra