Common Array Operations
Part of the Fundamentals section of Coddy's C++ journey — lesson 66 of 74.
Here are some common array operations:
- Find the sum of all elements in an array:
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
std::cout << "Sum: " << sum;- Find the average of elements in an array:
int numbers[] = {1, 2, 3, 4, 5};
double sum = 0;
for (int number : numbers) {
sum += number;
}
double average = sum / std::size(numbers);
std::cout << "Average: " << average;- Find the maximum element in an array:
int numbers[] = {1, 5, 2, 9, 3};
int max = numbers[0];
for (int i = 1; i < std::size(numbers); i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
std::cout << "Max: " << max;- Find the minimum element in an array:
int numbers[] = {1, 5, 2, 9, 3};
int min = numbers[0];
for (int i = 1; i < std::size(numbers); i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
std::cout << "Min: " << min;Challenge
EasyCreate a function named calculateStats that takes an array of doubles and the size of the array as input and performs the following operations:
- Calculates the sum of all elements in the array.
- Calculates the average of the elements in the array.
- Finds the maximum element in the array.
- Finds the minimum element in the array.
The function should return an array of doubles containing the sum, average, maximum, and minimum, in that order.
Important notes:
- Use the
sizeparameter to control your loop — do not usestd::size(). - To initialize
maxandmin, start them atarr[0]— this works correctly even when the array contains only negative numbers. - The pre-written code in
main()already allocates a dynamic array usingnewand frees it withdelete[]— you only need to allocate the result array inside your function usingnew double[4]and return it.
Suggested approach:
- Initialize
sum = 0,max = arr[0], andmin = arr[0]. - Loop from
i = 0toi < size, accumulating the sum and updating max/min as needed. - Calculate the average as
sum / size. - Allocate a new array with
new double[4], store the four results in order, and return it.
Cheat sheet
Common array operations in C++:
Sum of all elements:
int numbers[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}Average of elements:
int numbers[] = {1, 2, 3, 4, 5};
double sum = 0;
for (int number : numbers) {
sum += number;
}
double average = sum / std::size(numbers);Maximum element:
int numbers[] = {1, 5, 2, 9, 3};
int max = numbers[0];
for (int i = 1; i < std::size(numbers); i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}Minimum element:
int numbers[] = {1, 5, 2, 9, 3};
int min = numbers[0];
for (int i = 1; i < std::size(numbers); i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}Try it yourself
#include <iostream>
double* calculateStats(double arr[], int size) {
// You'll need to calculate 4 values before storing them in newArr
// Initialize variables for sum (start at 0), max, and min (both start at arr[0])
// Use a for loop to iterate through the array
// Inside the loop:
// - Add each element to sum
// - Compare each element with max and update if larger
// - Compare each element with min and update if smaller
// Calculate average = sum / size (after the loop)
double* newArr = new double[4];
newArr[0] = sum;
newArr[1] = average;
newArr[2] = max;
newArr[3] = min;
return newArr;
}
int main() {
int n;
std::cin >> n;
std::cin.ignore();
double arr[n];
for (int i = 0; i < n; i++) {
double val;
std::cin >> val;
arr[i] = val;
}
double* stats = calculateStats(arr, n);
std::cout << "Sum: " << stats[0] << std::endl;
std::cout << "Average: " << stats[1] << std::endl;
std::cout << "Maximum: " << stats[2] << std::endl;
std::cout << "Minimum: " << stats[3] << std::endl;
delete[] stats;
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison3Variables Part 2
Type DeclarationNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementConditional OperatorRecap - If ElseNested If - Else