3.6: Solving Arithmetic Expressions in MIPS Assembly
- Page ID
- 27111
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
Using the MIPS arithmetic operations covered so far, a program can be created to solve equations. For example the following pseudo code program, where the user is prompted for a value of x and the program prints out the results of the equation 5x2 + 2x + 3.
main { int x = prompt("Enter a value for x: "); int y = 5 * x * x + 2 * x + 3; print("The result is: " + y); }
This program is implemented in MIPS below.
Program 3-3: Program to calculate 5*x^2 + 2*x + 3 # File: Program3-3.asm # Author: Charles Kann # Purpose: To calculate the result of 5*x^ + 2*x + 3 .text .globl main main: # Get input value, x addi $v0, $zero, 4 la $a0, prompt syscall addi $v0, $zero, 5 syscall move $s0, $v0 # Calculate the result of 5*x*x + 2* x + 3 and store it in $s1. mul $t0, $s0, $s0 mul $t0, $t0, 5 mul $t1, $s0, 2 add $t0, $t0, $t1 addi $s1, $t0, 3 # Print output addi $v0, $zero, 4 # Print result string la $a0, result syscall addi $v0, $zero, 1 # Print result move $a0, $s1 syscall #Exit program addi $v0, $zero, 10 syscall .data prompt: .asciiz "Enter a value for x: " result: .asciiz "The result is: "