-1

I am trying to make a procedure that returns the sum of only odd numbers entered by the user and everything else is working fine except that the sum value always shows the last integer entered, if i sum all the numbers entered including even numbers then the output is correct so i am assuming maybe the condition is not right?

I tried different methods but i can't seem to figure out exactly where i got it wrong

This is my code, can someone please point out what's the problem here?

ArraySum proc USES esi ecx  
         mov eax, 0
         L1:
         test eax, 1
         jz L2
         add eax, [esi]
         add esi, 4
         loop L1
         L2:
         add esi,4
         loop L1


  ret
  ArraySum endp
Peter Cordes
  • 286,368
  • 41
  • 520
  • 731
rowl
  • 1
  • 1
  • if i remove the initialization of eax part this is the output: enter an integer: 1 enter an integer: 2 enter an integer: 3 enter an integer: 4 enter an integer: 5 the sum of odd integers: +6 – rowl May 16 '22 at 09:23
  • 1
    Remove the first `add esi, 4` / `loop L1` pair. You don't want a `loop` instruction right after another `loop` instruction. – Michael May 16 '22 at 09:24
  • I tried that but unfortunately i still got the wrong output, also every time i change the order of the same input numbers i get different results not sure why – rowl May 16 '22 at 09:32
  • Well, you haven't shown us the code that calls this function, nor the code the outputs the sum. So for all we know you could have bugs elsewhere in your code. – Michael May 16 '22 at 09:46
  • I added the entire code in the original post, can you please tell me if there is something i did wrong – rowl May 16 '22 at 10:14
  • 1
    You should take a closer look at where `esi` is pointing during various portions of your program's lifetime. – Michael May 16 '22 at 10:43
  • I changed the condition and a few other things in the loop and it worked, Thank you for the help greatly appreciate it! – rowl May 16 '22 at 12:37
  • This always returns zero because you test the current sum for being odd, not the value to maybe be added. I assume your test-case ended with a `0`, so that's just a coincidence. And if you fixed that, it would read past the end of the array for 2^32 iterations if the last element is odd, because of how `loop` works. Don't tail-duplicate the loop, jump over just the add. Anyway, use a debugger to single-step your code to catch obvious problems where the branching is a sign of a problem. – Peter Cordes May 16 '22 at 13:02

0 Answers0