Skip to content
The site is in test mode. All features are free for now.
MathAgora

C++ and Mathematics

Arrays, vectors and sequences

Arrays and vector, zero-based indexing, sum, maximum, prefix sums, progressions, sorting.

50 min 8 questions

01Arrays and vectors

int a[5] stores 5 integers: a[0], …, a[4]. Indices start at 0, so the kk-th term of a sequence (aka_k) lives in a[k-1]. Accessing outside the bounds (a[5]) is undefined behavior — C++ does not check it.

vector<int> v = {7, -2, 9}; is a dynamic array: v.size(), v.push_back(x). sort(v.begin(), v.end()) sorts in increasing order.

02Prefix sums and progressions

Prefix sums pi=a1+⋯+aip_i = a_1 + \dots + a_i are computed once (pi=pi−1+aip_i = p_{i-1} + a_i); then any range sum is a single subtraction: al+⋯+ar=pr−pl−1a_l + \dots + a_r = p_r - p_{l-1}.

An arithmetic progression in code: a[0] = a1; a[i] = a[i-1] + d; — check it with an=a1+(n−1)da_n = a_1 + (n - 1)d.

C++
vector<int> a = {2, 4, 6, 8};
vector<int> p(a.size());
p[0] = a[0];
for (size_t i = 1; i < a.size(); i++)
    p[i] = p[i - 1] + a[i];   // p = {2, 6, 12, 20}

Key formulas

  • Prefix sums

    pi=pi−1+ai,∑k=lrak=pr−pl−1p_i=p_{i-1}+a_i,\qquad \sum_{k=l}^r a_k=p_r-p_{l-1}
  • Arithmetic progression

    an=a1+(n−1)da_n=a_1+(n-1)d

Worked examples

Example 1

What does this code print?

C++
vector<int> v = {5, 3, 8};
v.push_back(1);
cout << v.size() << " " << v[3];