Sum of even numbers
A program that displays the sum of n even natural numbers.
Program source code
title .model small .stack 100h data segment public askUser db "Enter a number: \0" msgeven db "\nEven numbers: \0" msgres db "\nSum of even 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:[msgeven] ; 1st: Load the address of the msgeven variable into the ax register call PrintFormatString ; Call the PrintFormatString procedure mov cx, 1 ; Set the counter to 1 MainLoop: mov ax, 2 ; Copy the number 2 into the ax register mul cx ; Multiply the value in the ax register by the value in cx push ax ; 2nd: save the ax register value on the stack lea ax, ds:[fmtoutput] ; 1st: Load the address of the fmtoutput format string into the ax register call PrintFormatString ; Call the PrintFormatString procedure add sp, 2 ; Align the stack mov ax, 2 ; Copy the number 2 into the ax register mul cx ; Multiply the value in the ax register by the value in cx add numsum, ax ; Save the value of the ax register in the numsum variable inc cx ; Increment the counter register value by 1 cmp cx, number ; Compare the value of cx with the value in number jbe MainLoop ; If the value is below or equal to userInput, then jump to MainLoop push numsum ; 2nd: Save the numsum variable value on the stack lea ax, ds:[msgres] ; 1st: Load the address of the msgres format string into the ax register 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: 5
Even numbers: 2 4 6 8 10
Sum of even natural numbers: 30
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".