•

Check out our Community Blogs

Register and join over 40,000 other developers!

### Recent Blog Entries

• phi

I love this community !

• JackJames

hi i am jack i am seo expert jack james would love you to read new post

# MIPS Programming Implementing Loop For Any Given Number & Finding Median

computing computer-science computer-architecture

This topic has been archived. This means that you cannot reply to this topic.

### #1 sg81

sg81

CC Lurker

• Just Joined
• 1 posts

Posted 11 March 2015 - 01:27 AM

I need to find a solution on how to implement a loop using an entered number as iteration count:

```.data

num1:     .asciiz "\nEnter the first number: "
num2:      .asciiz "\nEnter the second number: "
num3:      .asciiz "\nEnter the third number: "
space: .asciiz ", "
Median: .asciiz " \nThe Median is : "

.text

main:
# Print the prompt to enter the first number
li \$v0,4
la \$a0, num1
syscall

# Entering the first number
li \$v0,5
syscall
move \$t2,\$v0

# Print the prompt to enter the second number
li \$v0,4
la \$a0, num2
syscall

# Entering the first number
li \$v0,5
syscall
move \$t3,\$v0

#print the prompt for the third number
li \$v0, 4
la \$a0, num3
syscall

# Entering the third number
li \$v0, 5
syscall
move \$t5,\$v0

# The if statement or conditional statement
bgt \$t2,\$t3, bigger
move \$t4,\$t3
bgt \$t4,\$t5, bigger1
move \$t6,\$t5

b endif

bigger:
move \$t4,\$t2

bigger1:
move \$t6,\$t4

sub \$t7,\$t6,\$t4
syscall

endif:

li \$v0, 4
la \$a0, Median
syscall

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

#END OF PROGRAM
li \$v0,10
syscall
```

For example, when 40 is entered, then the program will give all the odd numbers from 1 - 40.

Can someone also tell me how to get the median. The output for the median is always 0.

For example if the input is 1 2 3 then the median should be 2

Thanks

#### Attached Thumbnails

Edited by sg81, 11 March 2015 - 01:29 AM.

### #2 dargueta

dargueta

I chown trolls.

• Moderator
• 4854 posts

Posted 11 March 2015 - 05:28 PM

The reason why your median is always 0 is because you're storing your median in \$t7. Do not assume any of the t registers are preserved across function calls or system calls. T stands for temporary, and that's what they are. Functions are only required to preserve whatever's in the s registers (s0-s8) if they use them.

Your easiest solution would be to store your median in a variable in the data section, then load it into \$a0 just before your syscall to print it.

sudo rm -rf / && echo \$'Sanitize your inputs!'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download