Created
February 21, 2015 13:31
-
-
Save blog1729/388f551ce7065eda0eea to your computer and use it in GitHub Desktop.
Program to find the sum of first n positive integers using a loop where n is taken as input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Program to find the sum of first n natural numbers, where the user will input n, the program uses a loop even though there is a closed form answer. # | |
| .data | |
| cmd_prompt: | |
| .asciiz "Enter a positive integer: " | |
| ans_cmd: | |
| .asciiz "The answer is: " | |
| .text | |
| main: | |
| #Prompt | |
| li $v0, 4 | |
| la $a0, cmd_prompt | |
| syscall | |
| #Read integer | |
| li $v0, 5 | |
| syscall | |
| #store the integer into a saved temporary | |
| move $s0, $v0 | |
| #initialize s1, the number in the loop as zero | |
| li $s1, 0 | |
| #initiazle s2, the sum as zero | |
| li $s2, 0 | |
| for: | |
| blt $s0, $s1, endf | |
| add $s1, $s1, 1 | |
| add $s2, $s2, $s1 | |
| b for | |
| endf: | |
| # Print the ans_cmd string | |
| li $v0, 4 | |
| la $a0, ans_cmd | |
| syscall | |
| # Print the answer | |
| li $v0, 1 | |
| move $a0, $s2 | |
| syscall | |
| #Terminates the program | |
| li $v0, 10 | |
| syscall | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment