7.8: Example Program, Sum of Squares
- Page ID
- 55763
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
The following is a complete example program to find the sum of squares from 1 to n. For example, the sum of squares for 10 is as follows:
\[1^2 + 2^2 + \cdots + 102 = 385\nonumber\]
This example main initializes the n value to 10 to match the above example.
; Simple example program to compute the ; sum of squares from 1 to n. ; ********************************************** ; Data declarations section .data ; ----- ; Define constants SUCCESS equ 0 ; Successful operation SYS_exit equ 60 ; call code for terminate ; Define Data. n dd 10 sumOfSquares dq 0 ; ******************************************************* section .text global _start _start: ; ----- ; Compute sum of squares from 1 to n (inclusive). ; Approach: ; for (i=1; i<=n; i++) ; sumOfSquares += i^2; mov rbx, 1 ; i mov ecx, dword [n] sumLoop: mov rax, rbx ; get i mu1 rax ; i^2 add qword [sumOfSquares], rax inc rbx loop sumLoop ; ----- ; Done, terminate program. last: mov rax, SYS_exit ; call code for exit mov rdi, SUCCESS syscall ; exit with success
The debugger can be used to examine the results and verify correct execution of the program.