All lessons
LESSON 22/53Text and Array
Working Through an Array
GOALFind a total, an average, and the largest value.

Array + loop is where the real power is. Most problems are built on exactly this pair.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[100];
for (int i = 0; i < n; i++) cin >> a[i];
int sum = 0;
int best = a[0];
for (int i = 0; i < n; i++) {
sum = sum + a[i];
if (a[i] > best) best = a[i];
}
cout << "Sum: " << sum << endl;
cout << "Max: " << best << endl;
cout << "Avg: " << (double)sum / n << endl;
return 0;
}> what you see
(input: 4\n3 9 2 6) Sum: 20 Max: 9 Avg: 5
//LINE BY LINE
Watch it run
n = 4. Before the loop, sum is 0 and best is a[0], which is 3.
The four jobs you will do again and again
Sum and average:
int sum = 0;
for (int i = 0; i < n; i++) sum += a[i]; // нийлбэр
double avg = (double)sum / n; // дундажThe largest value — start from the first element:
int best = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > best) best = a[i];
}Searching — break as soon as you find it:
bool found = false;
for (int i = 0; i < n; i++) {
if (a[i] == target) { found = true; break; }
}Do not start a maximum search from int best = 0; — if every value is negative you get the wrong answer. Start from the first element.