C++: Sum and average

Read a list and summarise it.

What to build

A program that stores numbers in a vector.

Requirements

  • Read the numbers into a vector.
  • Print sum S and average A, with the average to two decimals.

Input

The first line has n. The second line has n whole numbers.

Output

Two lines.

Constraints

n is from 1 to 1000. Each number is from -1000 to 1000.

Example

Input:

3
1 2 3

Output:

sum 6
average 2.00

Why it works

vector<int> v(n) makes exactly the room needed, and v[i] works just as it does for an array.

Examples

Example 1 · Input
3
1 2 3
Expected output
sum 6
average 2.00
Example 2 · Input
2
1 2
Expected output
sum 3
average 1.50

Hints

Hint 1

Use vector<int> v(n), and read into v[i].

Hint 2

Convert to double before dividing.

Solution

Show one correct solution (try it yourself first)
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> v(n);
    int sum = 0;
    for (int& x : v) {
        cin >> x;
        sum += x;
    }
    cout << "sum " << sum << endl;
    cout << "average " << fixed << setprecision(2) << static_cast<double>(sum) / n << endl;
    return 0;
}

Lesson: Vectors →