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 -th term of a sequence () 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 are computed once (); then any range sum is a single subtraction: .
An arithmetic progression in code: a[0] = a1; a[i] = a[i-1] + d; — check it with .
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
Arithmetic progression
Worked examples
Example 1
What does this code print?
vector<int> v = {5, 3, 8};
v.push_back(1);
cout << v.size() << " " << v[3];What does this code print?
#include <iostream>
using namespace std;
int main() {
int a[5] = {3, 1, 4, 1, 5};
int s = 0;
for (int i = 0; i < 5; i++) s += a[i];
cout << s;
}Sample content: questions and lessons are illustrative and are not taken from official exams.
