# For-loop for adding several "n" integers

Page 1 of 1

## 2 Replies - 562 Views - Last Post: 04 June 2014 - 11:38 AM

### #1 Djhar

• New D.I.C Head

Reputation: 2
• Posts: 35
• Joined: 24-January 10

# For-loop for adding several "n" integers

Posted 04 June 2014 - 11:33 AM

Hello,

I'm just starting to learn MIPS assembly language in my comp org class and I was hoping someone could verify this code and that it works correctly. I believe it does when you input the first integer after you compile but then when it asks for a second integer input, it doesn't work properly. Also, it crashes with a arithmetic overflow when I input an integer less than the previous input (eg. 5 then 4). I'm using MARS to type, compile and run my code. Thanks!

```#################################################################
# 	This program aims to implement the following c code:
# 	for (i=0; i<n; i++)
# 	{
#		k = k + i;
# 	}
#################################################################

.data
str_1:	.asciiz "\nEnter a positive decimal integer => "
str_2:	.asciiz "The addition of these integers is "
.align	2
.text
.globl	main

main:
START:
la	\$a0, str_1	# system call to print prompt
li	\$v0, 4
syscall
li	\$v0, 5		# system call to read an integer
syscall
beq	\$v0, \$0, EXIT	# if ( input == 0 ), then we're done
addi	\$t3, \$v0, 0	# copy input to temporary register
addi	\$t2, \$0, 0	# set k = 0

LOOP:
beq	\$t0, \$t3, DONE	# if ( i == n ) then done
add	\$t2, \$t2, \$t0	# k = k + i
addi	\$t0, \$t0, 1	# i = i + 1 Counter
bne	\$t1, \$t3, LOOP	# if ( i =/= n ) then loop

DONE:
la 	\$a0, str_2	# system call to print answer prompt
li	\$v0, 4
syscall
addi	\$a0, \$t2, 0	# move count result to \$a0
li	\$v0, 1		# print the result
syscall
j	START		# begin again

EXIT:
li	\$v0, 10		# exit program
syscall

```

Is This A Good Question/Topic? 0

## Replies To: For-loop for adding several "n" integers

### #2 no2pencil

• Professor Snuggly Pants

Reputation: 6643
• Posts: 30,932
• Joined: 10-May 07

## Re: For-loop for adding several "n" integers

Posted 04 June 2014 - 11:36 AM

** Moved to Assembly **
Was This Post Helpful? 0

### #3 Djhar

• New D.I.C Head

Reputation: 2
• Posts: 35
• Joined: 24-January 10

## Re: For-loop for adding several "n" integers

Posted 04 June 2014 - 11:38 AM

no2pencil, on 04 June 2014 - 11:36 AM, said:

** Moved to Assembly **

That's weird, I selected "assembly" under the dropbox for the new topic and it posted it under other languages anyway
Was This Post Helpful? 0

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }