0

I try to calculate 4n^2 where n[1..10]. This is my code, but i can't understand why result is not printed in console. I tried with ShowUInt16 and without, but result is just black screen insead of 1540

.model small
.data
.stack 100h
.code
main:
    mov ax, @data
    mov ds, ax
    mov cx, 1
    mov bx, 0
l1:
    mov ax, cx
    mul ax
    shl ax, 1
    shl ax, 1
    add bx, ax
    cmp cx, 10
    jbe l1
    mov ax, bx
    call ShowUInt16
    mov ax, 4C00h
    int 21h
ShowUInt16       proc
        push    ax
        push    bx
        push    cx
        push    dx
        mov     bx,     10              
        mov     cx,     0               
        @@div:
                xor     dx,     dx      
                div     bx
                add     dl,     '0'     
                push    dx              
                inc     cx              
                test    ax,     ax      
        jnz     @@div                   
        @@show:
                mov     ah,     02h     
                pop     dx              
                int     21h             
        loop    @@show                  
    pop     dx
    pop     cx
    pop     bx
    pop     ax
        ret     
ShowUInt16       endp
end main

C++ analogical code so solve this equation

#include <iostream>
using namespace std;
 
int main(){
    int n;
    for(int i = 1; i <= 10; i++){
        n += 4*i*i;
    }
    cout<<n;
}
  • 1
    How is the `l1` loop ever going to end (i.e. how is `cx` ever going to become > 10)? – Michael Oct 27 '20 at 09:28
  • Use a debugger to single-step your code. Perhaps you wanted `dec cx` / `jnz l1`, with `cx` starting at `10`? – Peter Cordes Oct 27 '20 at 09:29
  • @PeterCordes `#include using namespace std; int main(){ int n; for(int i = 1; i <= 10; i++){ n += 4*i*i; } cout< – Женя Касьян Oct 27 '20 at 09:35
  • @Michael `cx` is compared with 10, and use `jbe` while condition is met – Женя Касьян Oct 27 '20 at 09:42
  • You left out the `i++` part in the asm. Which would have been obvious if you single-stepped your code in a debugger: you'd see `cx` wasn't changing. My point was that you can count `i` down towards 1 and get the same result, like `do {...} while(--i != 0)`, like a normal idiomatic asm loop. [Why are loops always compiled into "do...while" style (tail jump)?](https://stackoverflow.com/q/47783926) – Peter Cordes Oct 27 '20 at 10:15
  • @PeterCordes oh, just add `inc cx` after `cmp cx, 10` and its working – Женя Касьян Oct 27 '20 at 10:29
  • *after*??? `inc` does leave CF unmodified but it overwrites ZF, so your `jbe` condition isn't exactly `i<=10` anymore. Normally you'd increment *before* the `i<=10` check, if you want to match the C semantics. – Peter Cordes Oct 27 '20 at 10:52

0 Answers0