Search code examples
assemblyx86windbgmasmmasm32

Sum of the numbers between 1 to 100


I'm a newbish in ASM. I'm trying to accomplish a simple task - sum of the numbers between 1 to 100, eax will hold the sum.
e.g: 1 + 2 + 3 + .. + 100

So here's the relevant code:

    XOR eax, eax ;; Set eax to 0
MOV ecx, 100 ;; We will loop 100 times
my_loop:
    ADD eax, ecx ;; We add the ecx register value to eax, ecx decreses by 1 every iteration untill he reaches 0
LOOP my_loop
  ;;Exit the program, eax is the exit code
push eax
call ExitProcess

When I debug the exe file, eax is being 0. How is it possible?

BTW, is there any easy way to print the value of EAX to the console, instead of opening Windbg to check its value?


Solution

  • This program, a little bit adapted for FreshLib works like a charm. The core of the program is the same, I simply added some console output. (and well, it is FASM syntax) So, you simply missed to notice that the program is working properly.

    include "%lib%/freshlib.inc"
    
    @BinaryType console
    
    include "%lib%/freshlib.asm"
    
    start:
            InitializeAll
    
            XOR  eax, eax ;; Set eax to 0
            MOV  ecx, 100 ;; We will loop 100 times
    my_loop:
            ADD  eax, ecx ;; We add the ecx register value to eax, ecx decreses by 1 every iteration untill he reaches 0
            LOOP my_loop
      ;;Exit the program, eax is the exit code
            mov  ebx, eax
    
            stdcall NumToStr, ebx, ntsDec or ntsSigned
            stdcall FileWriteString, [STDOUT], eax
    
            stdcall FileReadLine, [STDIN]  ; in order to pause until ENTER is pressed.
    
            stdcall TerminateAll, ebx 
    
    @AllDataEmbeded
    @AllImportEmbeded