Arrays & Loops in Assembly… Code not outputting correct Values

By : love
Source: Stackoverflow.com
Question!

I have an array T with 10 values, specifically (if it matters) and in order: 2d, 5c, 5b, d3, 9b, 9a, 48, f1, e8, & 59.
In my code I am trying to find the sum, min, max, and average.
Well I get the sum and average but for some reason I have to divide it by 2 for the correct answer... weird. Now at one point my findMin code was working, (gave me 2d), but now it is not(just giving 0). findMax also gives me a value that does not even exist in the array. Here's the code:

done:   
mov ebx, 0      ;clear for loop counter
mov ecx, 0      ;clear array pointer
mov eax, [T]    ;base case for sum

findSum:
cmp ebx, 10
jge done1       ;if loop count = 10, done
add ecx, 4      ;point to next array value
add eax, [T+ecx]    ;add to register eax
inc ebx
mov sum, eax    ;store sum in var 'sum'
jmp findSum

done1:
;; resets regs for loop counter
mov ebx, 0
mov ecx, 0
mov eax, [T]    ;first val of table is min by default
jmp findMin

findMin:
;; finds the lowest value in table, first value is min by default
cmp ebx, 10     ;while ebx != 10
jge done2       ;else done
add ecx, 4      ;point to next value of array
inc ebx     ;increment loop counter
cmp [T+ecx], eax    ;if value at T is greater than eax(min) 
jge findMin     ;compare next value to min
mov eax, [T+ecx]    ;else value is less than min, assigns to reg eax
mov min, eax    ;assigns it to var min
jmp findMin

done2:
;; resets regs for loop  counter
mov ebx, 0
mov ecx, 0
mov eax, [T]    ;first val of table is max by default
jmp findMax

findMax:
;; finds the highest value in the table, first val is max by default
cmp ebx, 10     ;while ebx != 0
jge findAvg     ; else done
add ecx, 4      ;to point to next value in array
inc ebx     ;increment loop counter
cmp [T+ecx], eax    ;if value at array is less than max(eax)
jle findMax     ;compare next values
mov eax, [T+ecx]    ;else value is greater than max, assign to reg eax
mov max, eax    ;assign to var max
jmp findMax

sum, min, max are all declared as dwords.
Do you see something that I must be overlooking as to why:
a) the sum has to be divided by 2 for the correct sum?
b) my findMin and findMax segments aren't working? (min=0 & max = acc)

By : love


Answers

You are processing the first element outside the loops but still your counter starts from zero and goes to 10. That means, you will process 11 elements, with the 11th accessing whatever is after the array in memory.

Next time use a debugger to step through your code and see where it does something unexpected.

Note that x86 supports effective addressing in the form of [T ebx*4] which could simplify your code.

By : Jester


This video can help you solving your question :)
By: admin