Table of Contents

IronForgeCyber

Courses

Resources

Blog

Log In



IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. asm-101
  3. sum-array
3 min read

Sum an Array

This challenge brings loops and memory together: walk across an array stored in memory and total its elements in a register. The addressing trick at its center — reaching element i with a scaled index — is one you will use constantly.

Problem

Define an array of integers in memory and compute their sum in a register using a loop. Reach each element with scaled-index addressing rather than advancing a pointer by hand, and return the final sum as the program's exit status.

Hints

Open one hint at a time before reading the walk-through.

Hint 1
Store the array in section .data with dq (8-byte quadwords). Let the assembler count the elements for you: arrlen equ ($ - arr) / 8 is the byte span divided by the element size.
Hint 2
Reach element i with the scaled addressing from Memory: [arr + rcx*8], where rcx is the index and 8 is the size of each element.
Hint 3
This is the loop shape from Control Flow: add the element to a running total, inc the index, cmp it against the length, and conditionally jump back.

Walk-through

Use three registers: rax for the running sum (start it at zero with the xor rax, rax idiom), rcx for the index (also zeroed), and rdx to hold the element count. Each pass of the loop adds one element to the sum with add rax, [arr + rcx*8]. The rcx*8 is the key: because every element is 8 bytes, multiplying the index by 8 lands the effective address exactly on element rcx — the CPU does the arithmetic as part of the instruction.

Then inc rcx advances to the next index, cmp rcx, rdx checks whether we have reached the end, and jl jumps back while the index is still less than the length. Here is the array sitting in memory before the loop runs:

gdb
gef➤ break _startBreakpoint 1 at 0x401000gef➤ runBreakpoint 1, 0x0000000000401000 in _start ()gef➤ x/5dg &arr0x402000:       10      200x402010:       30      400x402020:       50

Five quadwords — 10, 20, 30, 40, 50 — laid out back to back, 8 bytes apart. (The line addresses jump by 0x10 only because x prints two quadwords per line.) The loop visits each one in turn.

Solution

nasm
1section .data
2    arr dq 10, 20, 30, 40, 50
3    arrlen equ ($ - arr) / 8
shell
$ ./sum; echo $?150

150 is 10 + 20 + 30 + 40 + 50 — the loop visited all five elements through [arr + rcx*8] and accumulated them in rax.

; byte span / element size = 5
4
5section .text
6 global _start
7_start:
8 xor rax, rax ; sum = 0
9 xor rcx, rcx ; index i = 0
10 mov rdx, arrlen ; loop limit
11.loop:
12 add rax, [arr + rcx*8] ; sum += arr[i]
13 inc rcx ; i++
14 cmp rcx, rdx ; i < len ?
15 jl .loop ; if so, repeat
16 mov rdi, rax ; exit code = sum
17 mov rax, 60
18 syscall