Array Operations — Working with Your List
Learn the essential array patterns: sum, average, and counting — skills you will use in every contest!
Open interactive version (quiz + challenge)Real-world analogy
Imagine you are a teacher collecting test scores from your class. You write all the scores in a list (that is your array). Then you add them all up to get the total (sum), divide by the number of students to get the average, and count how many students scored above 90 (counting). These three operations are the bread and butter of array problems!
What is it?
Array operations are the basic computations you perform on arrays — summing elements, finding averages, and counting elements that match certain conditions. These patterns form the foundation of nearly every competitive programming problem.
Real-world relevance
When a weather app shows the 'average temperature this week,' it sums all 7 daily temperatures and divides by 7. When a teacher calculates how many students passed, they count scores above the passing grade. These are array operations happening in real apps every day!
Key points
- The Accumulator Pattern — The accumulator pattern is the most important array pattern in CP. You start with a variable (like sum = 0), then loop through the array and add each element to it. By the end of the loop, you have the total sum. This pattern works for adding, multiplying, counting, and more!
- Finding the Sum — To find the sum of an array: create a variable sum = 0, then loop through every element and do sum += arr[i]. After the loop, sum holds the total. Use long long instead of int if the sum could be larger than 2 billion (which happens a lot in CP!).
- Finding the Average — The average is just the sum divided by the count. But be careful with integer division! If sum=7 and n=2, then 7/2 = 3 in integer math (not 3.5). To get the decimal answer, use (double)sum / n. Many CP problems ask for the integer average though, so read the problem carefully.
- Counting Elements — Counting is another accumulator pattern. Start with count = 0, then loop through the array and do count++ whenever an element meets your condition. How many numbers are positive? How many are even? How many are greater than 50? All use this same counting pattern.
- Finding Frequency — Sometimes you need to count how many times a specific value appears. This is called frequency counting. Loop through the array and increment a counter whenever arr[i] equals the target value. In more advanced problems, you will use a frequency array to count all values at once.
- Prefix Sum (Bonus Concept) — A prefix sum array stores the running total at each position. prefix[0] = arr[0], prefix[1] = arr[0]+arr[1], etc. This lets you find the sum of any range in O(1) time! It is a key technique in CP that turns slow solutions into fast ones.
- Using long long for Safety — In CP, always think about overflow. If n can be 100,000 and each element can be 1,000,000, then the sum can be 100,000,000,000 — way too big for int (max ~2 billion). Always use long long for sums, products, and anything that could get big. Better safe than sorry!
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
// 1. Find the sum
long long sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
cout << "Sum: " << sum << endl;
// 2. Find the average
double avg = (double)sum / n;
cout << "Average: " << avg << endl;
// 3. Count positive numbers
int positiveCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > 0) {
positiveCount++;
}
}
cout << "Positive numbers: " << positiveCount << endl;
// 4. Count even numbers
int evenCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
evenCount++;
}
}
cout << "Even numbers: " << evenCount << endl;
return 0;
}
// Input: 5
// 3 -1 4 -2 7
// Output: Sum: 11
// Average: 2.2
// Positive numbers: 3
// Even numbers: 2Line-by-line walkthrough
- 1. We read n numbers into an array — our standard input pattern.
- 2. For the sum, we start with sum = 0 (using long long for safety) and add each element.
- 3. For the average, we cast sum to double before dividing so we get decimal places.
- 4. For counting positives, we start with count = 0 and increment whenever arr[i] > 0.
- 5. For counting evens, we check arr[i] % 2 == 0 — the modulo trick for checking divisibility.
- 6. Each operation uses the same loop pattern — only the action inside changes.
- 7. This is the beauty of the accumulator pattern: one pattern, many uses!
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
cout << "Average: " << sum / n << endl;
return 0;
}
// Input: 4
// 3 4 3 4
// Expected Average: 3.5
// Actual Output: Average: 3Need a hint?
What type is 'sum'? What type is 'n'? What happens when you divide an integer by an integer in C++?
Show answer
The bug is integer division! Both sum (14) and n (4) are int, so 14/4 = 3 (the decimal part is thrown away). The fix is to cast to double: (double)sum / n. This gives 3.5. Also, sum should be long long for safety in bigger inputs!
Explain like I'm 5
Imagine you have a jar of marbles in different colors. To find the total, you count every marble one by one — that is a sum! To find the average, you share them equally among your friends and see how many each person gets. To count the blue ones, you just pick out every blue marble and count only those. Arrays work the same way!
Fun fact
The accumulator pattern (starting at 0 and adding up) was one of the first things ever done by computers! The very first electronic computers in the 1940s were literally built to add up long lists of numbers for things like artillery tables and census data. You are using a pattern that is older than your grandparents!
Hands-on challenge
Read an array of n integers. Find and print: (1) the sum of all elements, (2) the average (with 2 decimal places), (3) the count of negative numbers, (4) the count of numbers divisible by 5. Try to do it all in one pass through the array!
More resources
- Array Sum and Average — C++ Tutorial (Apna College)
- Prefix Sums — USACO Guide (USACO Guide)
- Array Operations Practice (Codeforces)