In: Computer Science
Write an assembly program In MASM assembler to calculate the sum of odd numbers only stored in a 16-bit integers array. The size of the array is provided in a separate variable. Use the following design:
Sum = 0
FOR i = 0 TO SizeOfArray - 1
IF Arr[i] % 2 = 1
Sum = Sum +
Arr[i]
END IF
END FOR
Assume that the array starts from the memory Location 500, size of array = 5 and the RESULT SUM IS stored at location 0.
So We will add the numbers at locations 501 and 503 (odd locations).
Find below a generic MASM Assembler code for adding numbers at odd places in an array!
400 | MOV SI, 500 | SI is the register storing the memory address! |
403 | MOV CL, [SI] | Register CL stores the value of Arr[i] |
405 | INC SI | |
406 | MOV CH, 00 | CH<-00 |
408 | MOV AL, 00 | Register AL stores the value of the variable SUM! |
40A | MOV BL, [SI] | BL<-[SI] |
40C | TEST SI, 01 |
SI AND 01 (THE MAIN CATCH) Explanation: In order to check if a number is odd we and it with the number 01. This works because if a number is odd it will have 1 as the LSB in its representation.(Eg. 1-> 0001 3->0011 5->0101 but 8->1000(Even)). Now, if you bitwise AND a number with 01 (0001): It will be zero at all places (since 0001 has zeroes at all places except LSB) except maybe at the LSB! If the number is even => 0 at LSB => AND will produce the number 0000. If the number is odd => 1 at LSB => AND will produce the number 0001. |
40F | JZ 413 | Jump to 413 memory location if zero flag is set |
411 | ADD AL, BL | SUM +=Arr[i] |
413 | INC SI | SI<-SI+1 |
414 | LOOP 40A | jump to 40A memory location if the content of CX is not equal to zero |
416 | MOV [600], AL | [600], AL FINAL STORAGE OF SUM |
41A | HLT | end |
P.S. Please give a thumbs up if you find the answer helpful!