Sum of odd numbers
A program that displays the sum of n odd natural numbers.
Program source code
title .model small .stack 100h data segment public askUser db "Enter a number: \0" msgodd db "\nOdd numbers: \0" msgres db "\nSum of odd 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:[msgodd] ; 1st: load the address of the msgodd variable into ax 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 dec ax ; Decrement the result value by 1 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 ax 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 dec ax ; Decrement the result value by 1 add numsum, ax ; Store the value of the ax register in the numsum variable inc cx ; Increment the value of the counter register by 1 cmp cx, number ; Compare the value of cx with the value in number jbe MainLoop ; If the value is less than or equal to userInput, 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 string 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: 5
Odd numbers: 1 3 5 7 9
Sum of odd natural numbers: 25
Example taken from the textbook "HANDYFAR - MASM (Evgeny Sergeevich Dovgopolov)".