Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. .data
  2. A: .word -4, 5, 8, -1 # int A[4]={-4,5,8,-1}; /* array of size 4 */
  3. A_size: .word 4 # int len=4;
  4. msg1: .string "Summation: "
  5. msg2: .string "+Ve Summation: "
  6. amsg1: .word msg1
  7. amsg2: .word msg2
  8. aA: .word A
  9. aA_size: .word A_size
  10.  
  11. .text
  12.  
  13. # int y = sums(A);
  14.  
  15. # int sums(int A[]){
  16. # int i, sum=0;
  17. # for(i=0; i<len;i++) /* loop to sum A elements */
  18. # sum=sum+A[i];
  19. # sumPos(A); /* calling SumPos() */
  20. # return sum;
  21. # }
  22.  
  23. # void sumPos(int A[]){
  24. # int i;
  25. # int sumPos=0;
  26. # for(i=0; i<len;i++){ /* loop to sum positive elements in A */
  27. # if(A[i]>0)
  28. # sumPos=sumPos+A[i];
  29. # }
  30. # printf("Sum of +ve: %d\n", sumPos); /* printing value in sumPos */
  31. # return;
  32. # }
  33.  
  34. main:
  35. lw t0, aA # Load Array A into t0
  36. lw t1, aA_size # Load the size of Array A (4) into t1
  37. lw t2, 0(t1) # Load t1 (4) into t2
  38. li t3, 0 # Initialize sum to 0
  39. li t4, 0 # Initialize index i to 0
  40. li t6, 0 # Initialize sumPos to 0
  41.  
  42. sums_loop:
  43. bge t4, t2, sums_exit # If i >= 4, exit loop
  44. slli t5, t4, 2 # i * 4 (shift left by 2 to multiply by 4)
  45. add t5, t5, t0 # Calculate address of A[i]; (i*4) + A
  46. lw a0, 0(t5) # Load A[i] into a0
  47. add t3, t3, a0 # sum += A[i]
  48. addi t4, t4, 1 # Increment i by 1
  49. j sums_loop # Repeat loop
  50.  
  51. sums_exit:
  52.  
  53. lw t6, amsg1
  54. la a0, msg1 # Load address of "Summation: " into a0
  55. sout t6 # Output "Summation: "
  56. dout t3 # Output sum
  57. nl
  58.  
  59. jal sumPos # Call sumPos
  60. la a0, msg2 # Load address of "+Ve Summation: " into a0
  61. sout a0 # Output "+Ve Summation: "
  62. mv a0, a1 # Move sumPos value to a0 (for printing purposes)
  63. sout a0 # Output sumPos
  64. halt
  65.  
  66.  
  67. sumPos:
  68. li t4, 0 # Initialize index i to 0
  69. li t6, 0 # Initialize sumPos to 0
  70.  
  71. sumPos_loop:
  72. bge t4, t2, sumPos_exit # If i >= 4, exit loop
  73. slli t5, t4, 2 # i * 4 (shift left by 2 to multiply by 4)
  74. add t5, t5, t0 # Calculate address of A[i]; (i*4) + A
  75. lw a1, 0(t5) # Load A[i] into a1
  76. blt a1, zero, skip_positive # If A[i] < 0, skip adding to sumPos
  77. add t6, t6, a1 # sumPos += A[i]
  78.  
  79. skip_positive:
  80. addi t4, t4, 1 # Increment i by 1
  81. j sumPos_loop # Repeat loop
  82.  
  83. sumPos_exit:
  84. mv a1, t6 # Move sumPos value to a1
  85. jr ra # Return from sumPos
  86.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement