Array CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

medium
Write pseudocode to find the sum of all elements in an array `nums = [4, 7, 2, 9]`.

Solution

  1. 1
    Step 1: SET total = 0.
  2. 2
    Step 2: FOR i = 0 TO LENGTH(nums) - 1: total = total + nums[i].
  3. 3
    Step 3: Trace: total = 0+4=4, 4+7=11, 11+2=13, 13+9=22. OUTPUT 22.

Answer

2222
Iterating through an array with a loop is a fundamental pattern. The accumulator pattern (initialise, loop, accumulate) is used for sums, counts, and many other operations.

About Array

An ordered collection of values stored together under a single name and accessed by their numeric index position. Arrays allow you to store, retrieve, and manipulate multiple related values efficiently using loops and index-based access.

Learn more about Array โ†’

More Array Examples