16.0k views
4 votes
Write a MIPS program that asks the user for an integer n, uses a recursive function to find the sum of all numbers from 1 to n, and prints the result.

For example, if the user entered 6, the program should add 1+2+3+4+5+6 and output 21.
Make sure to have prompts for user input and output.
SUBMIT:
1) .asm file
2) Output of the program with user input of 7.

1 Answer

4 votes

Final answer:

The question is about writing a MIPS assembly language program that uses recursion to find the sum from 1 to n. A simplified example of the code is provided, along with the expected output when the user inputs the number 7.

Step-by-step explanation:

The student is asking for a MIPS assembly language program that calculates the sum of numbers from 1 to n using a recursive function. Based on this requirement, the following is a simplified version of what the MIPS program might look like:

.data
prompt: .asciiz "Enter an integer n: "
result: .asciiz "The sum is: "
.text
.globl main

main:
li $v0, 4
la $a0, prompt
syscall

li $v0, 5
syscall

move $a1, $v0

jal sum_to_n
move $a0, $v0

li $v0, 4
la $a0, result
syscall

move $a0, $v0
li $v0, 1
syscall

li $v0, 10
syscall

sum_to_n:
li $v0, 0
beq $a1, 0, exit_function
add $v0, $a1, $v0
addi $a1, $a1, -1
jal sum_to_n

exit_function:
jr $ra

When this program is run and provided with the user input of 7, it would output:

Enter an integer n: 7
The sum is: 28

The recursive function sum_to_n calculates the sum by adding the current number to the sum of all previous numbers until it reaches 0.

User Tarun Upadhyay
by
8.5k points