N natural numbers and their sum
The program asks the user for a number n, prints the first n natural numbers and computes their sum.
Program source code
title .model small .stack 100h data segment public askUser db "Enter a number: \0" msgout db "\nNatural numbers: \0" msgres db "\nSum of natural numbers: %d\0" fmtinput db "%d" fmtoutput db "[%d] \0" number dw ? numsum dw ? data ends code segment public ; Start of the code segment assume ds:data, cs:code include Handyfar.inc ; Include the file with functions main proc ; Start of the main procedure call SetDataSegment ; Call the SetDataSegment procedure lea ax, ds:[askUser] ; Load the address of the askUser variable into ax call WriteString ; Call the WriteString procedure lea ax, ds:[number] ; Load the address of the number variable into the ax register push ax ; 2nd: save the ax register value on the stack lea ax, ds:[fmtinput] ; 1st: load the address of the fmtinput format string into ax call ScanFormatString ; Call the ScanFormatString procedure add sp, 2 ; Align the stack lea ax, ds:[msgout] ; 1st: load the address of the msgout variable into ax call PrintFormatString ; Call the PrintFormatString procedure mov cx, 1 ; Set the cx counter to 1 MainLoop: push cx ; 2nd: save the value of the cx counter register on the stack lea ax, ds:[fmtoutput] ; 1st: load the address of the fmtoutput format string into ax call PrintFormatString ; Call the PrintFormatString procedure add sp, 2 ; Align the stack add numsum, cx ; Add the value of the cx register to the numsum variable inc cx ; Increment the cx counter by 1 cmp cx, number ; Compare the value of the cx register with the value in number jbe MainLoop ; If CX is less than or equal to number, jump to MainLoop push numsum ; 2nd: save the value of the numsum variable on the stack lea ax, ds:[msgres] ; 1st: load the address of the msgres variable into ax call PrintFormatString ; Call the PrintFormatString procedure add sp, 2 ; Align the stack xor al, al ; Clear the al register call ExitProcess ; Call the ExitProcess procedure main endp ; End of the main procedure code ends ; End of the code segment end main ; End of file. The main procedure is the entry point
Enter a number: 7
Natural numbers: [1] [2] [3] [4] [5] [6] [7]
Sum of natural numbers: 28
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".