N 个自然数及它们的和

程序询问用户数字 n,输出前 n 个自然数并计算它们的和。

程序源代码

title Author: Dovgopolov Evgeny Sergeevich

.model small
.stack 100h

data segment public
    askUser   db "Enter the number: \0"
    msgout    db "\nNatural numbers: \0"
    msgres    db "\nThe sum of the natural numbers is: %d\0"
    fmtinput  db "%d"
    fmtoutput db "[%d] \0"
    number    dw ?
    numsum    dw ?
data ends

code segment public                 ; 代码段的开始
    assume  ds:data, cs:code
    include Handyfar.inc            ; 引入包含函数的文件

    main proc                       ; 过程 main 的开始
        call    SetDataSegment      ; 调用过程 SetDataSegment

        lea     ax, ds:[askUser]    ; 把变量 askUser 的地址装入寄存器 ax
        call    WriteString         ; 调用过程 WriteString

        lea     ax, ds:[number]     ; 把变量 number 的地址装入寄存器 ax
        push    ax                    ; 第 2 个:把寄存器 ax 的值保存在堆栈中
        lea     ax, ds:[fmtinput]   ; 第 1 个:把格式字符串 fmtinput 的地址装入寄存器 ax
        call    ScanFormatString    ; 调用过程 ScanFormatString
        add     sp, 2               ; 对齐栈

        lea     ax, ds:[msgout]     ; 第 1 个:把变量 msgout 的地址装入寄存器 ax
        call    PrintFormatString   ; 调用过程 PrintFormatString

        mov     cx, 1               ; 把计数器 cx 设为 1

    MainLoop:
        push    cx                  ; 第 2 个:把计数寄存器 cx 的值保存在堆栈中
        lea     ax, ds:[fmtoutput]  ; 第 1 个:把格式字符串 fmtoutput 的地址装入寄存器 ax
        call    PrintFormatString   ; 调用过程 PrintFormatString
        add     sp, 2               ; 对齐栈

        add     numsum, cx          ; 把寄存器 cx 的值加到变量 numsum

        inc     cx                  ; 把计数器 cx 增加 1
        cmp     cx, number          ; 把寄存器 cx 的值与 number 中的值进行比较
        jbe     MainLoop            ; 如果 CX 的值小于或等于 number,则跳转到 MainLoop

        push    numsum              ; 第 2 个:把变量 numsum 的值保存在堆栈中
        lea     ax, ds:[msgres]     ; 第 1 个:把变量 msgres 的地址装入寄存器 ax
        call    PrintFormatString   ; 调用过程 PrintFormatString
        add     sp, 2               ; 对齐栈

        xor     al, al             ; 把寄存器 al 清零
        call    ExitProcess         ; 调用过程 ExitProcess
    main endp                       ; 过程 main 的结束

code ends                           ; 代码段的结束
end main	                        ; 文件结束。入口点指定为过程 main

Enter the number: 7
Natural numbers: [1] [2] [3] [4] [5] [6] [7]
The sum of the natural numbers is: 28

示例取自教材 "HANDYFAR - MASM(多夫戈波洛夫·叶夫根尼·谢尔盖耶维奇)".