Thursday, March 26, 2020

Compute the sum of N consecutive numbers

This is a sample MIPS assembler code to compute the sum of N consecutive numbers, where N is an integer entered by the user. The code is fully commented.

Launch EzMIPS, copy the following MIPS code and paste it into EzMIPS, the MIPS assembler editor & simulator. Assemble, Run.

# --- compute the sum of N consecutive integers: 1 + 2 + 3 + ... + N --- #

.data

szNumbeOfIntegers: .asciiz "Enter number of integers (N): "
szSumIs:           .asciiz "Sum = "
szLF:              .asciiz "\n"

# ---------------------------------------------------------------------- #

.text

main:

# ...................................................................... #
    
    # Print "Enter number of integers (N): "
    li $v0, 4                      # print string syscall code = 4
    la $a0, szNumbeOfIntegers      # load address of szNumbeOfIntegers
    syscall                        # print it!

# ...................................................................... #

    # Get N from user
    li $v0, 5                      # read integer syscall code = 5
    syscall                        # get it!
    move $t0, $v0                  # keep N in $t0

# ...................................................................... #

    # Initialize registers
    ori $t1, $zero, 0              # initialize counter $t1=0
    ori $t2, $zero, 0              # initialize sum $t2=0

# ...................................................................... #

    # perform the addition!
loop:
    addi $t1, $t1, 1               # $t1 = $t1 + 1 (counter++)
    add $t2, $t2, $t1              # $t2 = $t2 + $t1 (sum = sum + counter)
    bne $t0, $t1, loop             # if conter != N, loop

# ...................................................................... #

    # Print "Sum = "
    li $v0, 4                      # print string syscall code = 4
    la $a0, szSumIs                # load address of szSumIs
    syscall                        # print it!

# ...................................................................... #

    # Print integer sum (=$t2)
    li $v0, 1                      # print integer syscall code = 1
    move $a0, $t2
    syscall                        # print it!

# ...................................................................... #

    # Print new line
    li $v0, 4                      # print string syscall code = 4
    la $a0, szLF                   # load address of szLF
    syscall                        # print it!         

# ...................................................................... #

    li $v0, 10                     # exit syscall = 10
    syscall                        # exit

# ---------------------------------------------------------------------- #

Please let me know of any suggestions or bugs regarding the code above.

Regards,

Antonis

No comments:

Post a Comment