Skip to content
The Chat Archive
Human-written demonstration (OpenAssistant volunteers)· OpenAssistant (human-written) OpenAssistant Conversations (oasst2)

Convert this MIPS assembly Fibonacci function code to C. It is a simple Fibonacci…

In OpenAssistant data, “assistant” turns were written by human volunteers as demonstrations. They are not model outputs.
  1. User

    Convert this MIPS assembly Fibonacci function code to C. It is a simple Fibonacci function.

    
    fib:
        addi $sp, $sp, -12    ; Allocate space on the stack
        sw $ra, 8($sp)        ; Save the return address
        sw $s0, 4($sp)        ; Save the base case value
        sw $s1, 0($sp)        ; Save the previous value
    
        bgtz $a0, calculate   ; Handle base cases
    
        li $v0, 0             ; Base case: fib(0) = 0
        j exit
    
    calculate:
        li $s0, 0             ; Initialize base cases
        li $s1, 1
    
        beq $a0, 1, return    ; Handle second base case
    
        addi $a0, $a0, -1     ; Recursive case
        jal fib
        move $t0, $v0         ; Save the previous value
    
        addi $a0, $a0, -1
        jal fib
        add $v0, $t0, $v0     ; Add previous value to current value
    
    return:
        move $v0, $s1         ; Return the current value
    
    exit:
        lw $s1, 0($sp)        ; Restore saved registers
        lw $s0, 4($sp)
        lw $ra, 8($sp)
        addi $sp, $sp, 12     ; Deallocate stack space
        jr $ra                ; Return to the calling function
    
    
    
  2. Assistant

    Here is a version of the code converted back to C:

    #include <stdio.h>
    
    // Function to calculate the nth Fibonacci number
    int fibonacci(int n) {
        // Allocate space on the stack
        // Save the return address
        // Save the base case value
        // Save the previous value
    
        // Handle base cases
        if (n <= 0) {
            // Base case: fib(0) = 0
            return 0;
        } else if (n == 1) {
            // Initialize base cases
            // Handle second base case
            // Return the current value
            return 1;
        } else {
            // Recursive case
            // Save the previous value
            // Add previous value to current value
            return fibonacci(n-1) + fibonacci(n-2);
        }
    }
    
    int main() {
        int number;
        printf("Enter a number: ");
        scanf("%d", &number);
        printf("Fibonacci of %d = %d\n", number, fibonacci(number));
    
        // Restore saved registers
        // Deallocate stack space
        // Return to the calling function
        return 0;
    }