Mips recursion sum of digits -
so understand logic behind how calculate sum of digits. wondering whether recursive function correct. assume user entered number or wants digit sum , stored in $v0.
sum2: li $s0, 0 move $a1, $v0 li $s1, 0 li $s2, 10 # adjusting stack frame size store 3 words addi $sp, $sp,-12 # these sum value, return address, , number sw $s1, 0($sp) sw $ra, 4($sp) sw $a1, 8($sp) loop2: bne $s0, $a1, sum3 move $a0, $s1 li $v0, 1 syscall lw $s1, 0($sp) lw $ra, 4($sp) lw $a1, 8($sp) addi $sp, $sp 12 jr $ra sum3: div $t0, $a1, $s2 mfhi $t0 add $s1, $s1, $t0 div $t1, $a1, $s2 mflo $a1 j loop2
if logic isn't clear first checking see if number doesn't equal 0 , if doesn't modulus of number divided 10 , add sum 0 , divide user input number 10 , continue call function till number becomes zero. had 1 quick last question. in mips recursive function or iterative function execute faster?
your implementation corresponds this:
int sum_digits(int n) { int res = 0; while (n != 0) { res += n % 10; n /= 10; } return res; }
actually you're printing result rather returning it, that's beside point. it's iterative function.
a recursive implementation this:
int sum_digits(int n) { return (n >= 10) ? ((n % 10) + sum_digits(n / 10)) : (n % 10); }
i'll leave translate mips assembly know algorithm looks like.
Comments
Post a Comment