Five patterns worth understanding
Use sums, counts, best-so-far candidates, products, and flags to process a stream.
Sum the values; count the matches
A sum adds the value itself; a count adds one when a condition matches. Both start at zero because no data has been processed. After every iteration, explain exactly what each accumulator represents.
For scores 40, 50, 80, 90, the total is 260 and the number passing at 50 or above is 3. One read can update both. A statement that remains true as the loop advances is called a loop invariant.
#include <iostream>
#include <iomanip>
int main() {
int n = 0;
std::cin >> n; // 1 <= n <= 100000; each score is 0..100.
long long sum = 0;
int passed = 0;
for (int i = 0; i < n; ++i) {
int score = 0;
std::cin >> score;
sum += score;
if (score >= 50) { ++passed; }
}
std::cout << sum << ' ' << passed << '\n';
std::cout << std::fixed << std::setprecision(2)
<< static_cast<double>(sum) / n << '\n';
return 0;
}Start a maximum from a real value
For a nonempty list, read the first actual value into best and compare the remaining n − 1 values with it. Replace best only when the new value is larger. To find a minimum, reverse the comparison.
Zero is not a safe initial maximum: for [−8, −3, −10], it is larger than every input and would give the wrong answer. A one-value list needs no comparisons after reading its first element.
Products start at one
For factorial, start answer at 1 and multiply by 1 through n. The zero-iteration case leaves 0! = 1. Under the source constraint 0 ≤ n ≤ 20, long long is sufficient; 21! exceeds a signed 64-bit integer.
Optional extension: calculate a small a to the power b by multiplying by a exactly b times, beginning at one. This requires b ≥ 0 and bounds that keep every product representable. The ^ symbol is not a power operator.
Flags remember a lasting fact
To remember whether any negative appeared, start found = false and set it to true on a negative. Do not set it back to false on a later nonnegative value: the earlier observation remains true.
Sums, counts, extrema, and flags often need only one value at a time. You do not need an array just because the input has many values. Store a sequence only when you must revisit it later.
Which initial values match sum, product, and maximum of a guaranteed nonempty list?
Turn the idea into code
Read 1 ≤ n ≤ 100000 followed by n values in [−10⁹, 10⁹]. Print their maximum without storing the whole list.
Give me a hint
The first read establishes the candidate. Exactly n − 1 reads remain.
Show the explained solution
After each read, best is the maximum of everything consumed. This uses one running candidate and works for equal values, all-negative values, and n = 1.
#include <iostream>
int main() {
int n = 0;
std::cin >> n;
long long best = 0;
std::cin >> best;
for (int i = 1; i < n; ++i) {
long long x = 0;
std::cin >> x;
if (x > best) { best = x; }
}
std::cout << best << '\n';
return 0;
}Your notes
Mark complete when you can explain it yourself.