Translate the following C code into MIPS assembly: #include <stdio.h> #include <
ID: 3563551 • Letter: T
Question
Translate the following C code into MIPS assembly:
#include <stdio.h>
#include <stdlib.h>
void Error (char vName);
int GetInput(char vName);
int main (void)
{
int a = 0, b = 0, c = 0, x = 0, result = 0;
printf("Enter values for a, b, c, and x when prompted. ");
printf("Each value can have a maximum of two digits. ");
a = GetInput('a');
b = GetInput('b');
c = GetInput('c');
x = GetInput('x');
result = (a * x * x) + (b * x) + c;
printf("ax^2 + bx + c is %d ", result);
return 0;
}
void Error (char vName)
{
printf("Error: Variable %c needs to be one or two digits.", vName);
exit(1);
}
int GetInput(char vName)
{
int v = 0;
printf("Enter a value for %c: ", vName);
scanf(" %d", &v);
if (v < -99 || v > 99)
{
Error(vName);
}
return v;
}
Explanation / Answer
.data
string: .asciiz "Enter values for a, b, c, and x when prompted. "
string1: .asciiz "Each value can have a maximum of two digits. "
string2: .asciiz "ax^2 + bx + c is "
string3: .asciiz "Error: Variable "
string4: .asciiz " needs to be one or two digits. "
string5: .asciiz "Enter a value for "
string6: .asciiz ": "
.text
main :
#int main (void)
#{
# int a = 0, b = 0, c = 0, x = 0, result = 0;
# printf("Enter values for a, b, c, and x when prompted. ");
li $v0,4
la $a0,string
syscall
# printf("Each value can have a maximum of two digits. ");
li $v0,4
la $a0,string1
syscall
# a = GetInput('a');
li $a1,'a'
jal GetInput
move $s0,$a0
# b = GetInput('b');
li $a1,'b'
jal GetInput
move $s1,$a0
# c = GetInput('c');
li $a1,'c'
jal GetInput
move $s2,$a0
# x = GetInput('x');
li $a1,'x'
jal GetInput
move $s3,$a0
# result = (a * x * x) + (b * x) + c;
mult $s3,$s3 #x*x
mflo $t0
mult $t0,$s0#a*x*s
mflo $t0
mult $s1,$s3 #b*x
mflo $t1
add $t0,$t0,$t1 #ax2+bx
add $t0,$t0,$s2 #ax2+bx+c
# printf("ax^2 + bx + c is %d ", result);
li $v0,4
la $a0,string2
syscall
li $v0,1
addi $a0,$t0,0
syscall
# return 0;
li $v0,10
syscall
#}
#void Error (char vName)
Error:
#{
# printf("Error: Variable %c needs to be one or two digits.", vName);
li $v0,4
la $a0,string3
syscall
li $v0,11
move $a0,$a1
syscall
li $v0,4
la $a0,string4
syscall
# exit(1);
li $v0,10
syscall
#}
#int GetInput(char vName)
GetInput:
#{
# int v = 0;
# printf("Enter a value for %c: ", vName);
li $v0,4
la $a0,string5
syscall
li $v0,11
move $a0,$a1
syscall
li $v0,4
la $a0,string6
syscall
# scanf(" %d", &v);
li $v0,5
syscall
#a in $s0
move $a0,$v0
# if (v < -99 || v > 99)
li $t0,-100
blt $v0,$t0, callerror
li $t0,100
bgt $v0,$t0, callerror
# return v;
jr $ra #return to caller
#}
# {
# Error(vName);
# }
callerror:
jal Error
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.