hi there! i cant figure out how i could program a little function in assembly using the PCSPIM environment.
the function i want to program with recursion is:

func(n) = func(n-1) + (n-1)

this is similiar to the fibonnaci function which is:

fib(n) = fib(n-1) + fib(n-2)

and the code for the fibonnaci can be found here:

how can i change in order to make it work with:

func(n) = func(n-1) + (n-1)

i tried plenty of times but i find it hard! all help will be greately appreciated!
thanks! :)

Dani AI

Generated

A compact note for the recurrence in 's original post: the recurrence func(n) = func(n-1) + (n-1) has a simple closed form once a base case is fixed. With func(0) = 0 (equivalently func(1) = 0) the solution is func(n) = n*(n-1)/2 — a triangular number. Quick derivation: f(n)-f(0) = sum_{k=1..n}(k-1) = n(n-1)/2. Computing the formula is O(1) and avoids O(n) recursion.

If an explicit recursive MIPS implementation in PCSpim is required, follow the MIPS calling convention: use $a0 for the argument and return the result in $v0. Before the recursive jal, save $ra (it will be overwritten) and any registers you need to preserve (or push the original n to the stack). Typical flow: check base case and return, set up stack frame and save $ra/saved registers, put n-1 in $a0 and jal the function, add (n-1) to the returned value in $v0, restore registers/$ra, then jr $ra. Keep a correct prologue/epilogue so the simulator stack stays consistent.

Notes and cautions: recursion here is linear-depth O(n) and consumes stack space — for large n prefer the closed form or an iterative loop. Tail recursion with an accumulator is another option if you want recursion without growing the stack as much. Also watch 32-bit overflow on PCSpim. For background on the formula and simulator calling-frame conventions see Triangular number and . later reported they sorted it, and 's nudge about function prologues/epilogues points exactly to the register-save steps above.

Recommended Answers

All 2 Replies

Do you know how to write functions already?

i have sorted it. dont worry.
thanks anyway!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.