Pointer Arithmetic

Lab C++ Intermediate 20 points

Read n integers into a vector. Using a pointer from v.data() and pointer arithmetic, print every second element and the sum of all elements.

Input

Line 1: n. Line 2: n integers.

Output

Two lines.

Example

Input

6
10 20 30 40 50 60

Output

10 30 50
210
Sample input available Sample output available
Editor
C++

Hints

v.data() points at the first element; begin + n is one past the end.

Solution explanation

Iterators generalise exactly this pointer pattern.

Show solution
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    for (int &x : v) cin >> x;
    const int *begin = v.data();
    const int *end = begin + n;
    bool first = true;
    for (const int *p = begin; p < end; p += 2) {
        cout << (first ? "" : " ") << *p;
        first = false;
    }
    cout << "\n";
    long long sum = 0;
    for (const int *p = begin; p != end; ++p) sum += *p;
    cout << sum << "\n";
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD