4/4/08

Simple MIPS counter

This a simple MIPS program. User is asked for a number. If user gives a number from 1 to 20 then the program prints all the numbers from 1 to the number the user inputed.
If user gave a number out of range program asks again for a valid number.
The same program in C is here.

.data
str1: .asciiz " Please give an integer from 1 to 20 : "
errormsg: .asciiz " Out of range (1-20). \n"
nline: .asciiz "\n" #new line
.text
error:
li $v0,4
la $a0,errormsg
syscall #print error msg
j get
.globl main # label "main" must be global
main:
addi $s0,$zero,21 #s0=21
get:
li $v0,4
la $a0,str1
syscall #print string1
li $v0,5
syscall #read int
slt $s1,$v0,$s0 #$s1=($v0<$s0) if(x<21) $s1=1
beq $s1,$zero,error #if $s1=0 goto error
blez $v0,error #if ($v0<=0) goto error
move $t0,$v0
add $t1,$0,$0
loop:
addi $t1,$t1,1 #$t1++
li $v0,1
move $a0,$t1
syscall #print int
li $v0,4
la $a0,nline
syscall #print nline
slt $t2,$t1,$t0 #$t2=($t1<$t0)
bnez $t2,loop #if $t2!=0 goto loop
li $v0,10 #exit program
syscall

Example of output is:

Please give an integer from 1 to 20: 35 Out of range (1-20).
Please give an integer from 1 to 20: -5 Out of range (1-20).
Please give an integer from 1 to 20: 5
1
2
3
4
5

I hope that this post was helpful for you. Maybe you would like to see MIPS Bubble sort.
Del.icio.us

1 comment:

Anonymous said...

Thanks a ton dude

Related Posts Plugin for WordPress, Blogger...