Back to track
#98 Easy Foundations

For Loop Sum

Open the editor

Problem

Read n then n integers and print their sum. The classic accumulate loop.

Constraints

1 <= n <= 200000, -10^9 <= each value <= 10^9

Input

Line 1: n. Line 2: n integers.

Output

The sum.

The idea

Concept

The accumulator has to be wide enough for the total, not just for each element: 200000 values of 10^9 overflow a 32-bit int long before the loop ends. That mismatch is the bug this problem exists to teach.

Approach

Loop n times, adding each value into a long long accumulator.

Hints

  1. 1

    Size the accumulator for the total, not the elements.

  2. 2

    n * 10^9 needs 64 bits.

  3. 3

    One pass is enough; no array is needed.

Worked solution

Reference solution

Time: O(n) · Space: O(1)

One correct implementation. Any approach that satisfies the constraints is equally valid.

#include <bits/stdc++.h>
using namespace std;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n;
  if (!(cin >> n)) return 0;
  long long sum = 0;
  for (int i = 0; i < n; i++) {
    long long x;
    cin >> x;
    sum += x;
  }
  cout << sum << '\n';
  return 0;
}

© 2026 ChitChat