AI Computer Science Academy · Faisalabad

C++ Foundations

Sum a vector with a function

Task 52 of 56 C++ Capstone: structs, maps and errors
All tasks
Read first Task 52

Sum a vector with a function

`std::vector` grows as you push into it, and a range-based `for` reads each element without an index.

Task

Task: Sum a vector with a function. What does this program print?

The editor already contains a starting point. Change it until every check passes — the Next task button unlocks when it does.

What you start with
#include <iostream>
#include <vector>
using namespace std;

int total(const vector<int>& marks) {
    int sum = 0;
    for (int mark : marks) {
        sum += mark;
    }
    return sum;
}

int main() {
    vector<int> marks = {850, 920, 780, 640};
    cout << "Total: " << total(marks) << endl;
    cout << "Average: " << total(marks) / marks.size() << endl;
    return 0;
}
C++ 1 automatic check Capstone: structs, maps and errors
Code editor Ctrl + Enter runs
Run your code to see the output and the checks.
Your result

Submit your code to see results

Write your code in the middle column and press Run code.

Checks on this task:

  • Check 1

Track progress

0 of 56 tasks complete

Next task unlocks when every check passes.

Sign in to keep your code and certificates.

Next task (pass every check first)