Sum of Array Elements in C++
In this exercise, you will create a program that calculates the total sum of all elements within an array. Summing data is a core operation in programming, essential for applications ranging from statistical analysis and financial reporting to real-time data processing.
The goal is to master the use of accumulation variables and iteration logic. You will implement a function that traverses the array, adds each value to a running total, and returns the final result.
Logic Components
1. Initialization
Start with a sum variable initialized to zero. This acts as your accumulator throughout the process.
2. Array Traversal
Use a for or range-based loop to visit every index of the array from 0 to size - 1.
3. Accumulation
Use the += operator to add the current element's value to your total sum during each iteration.
Pro Tip:
When working with very large numbers, consider using long long instead of int for the sum variable to prevent integer overflow.
Learning Objectives
- 1. Declare and initialize an integer array with sample data.
- 2. Create a modular function
sumArrayto handle the logic. - 3. Practice the accumulator pattern using loops.
- 4. Output the final result clearly in the console.
Solution Implementation
#include <iostream>
using namespace std;
// Function to calculate the sum of array elements
int sumArray(int arr[], int size) {
int sum = 0; // Accumulator variable
// Loop through the array to add each element
for (int i = 0; i < size; i++) {
sum += arr[i]; // sum = sum + current element
}
return sum; // Return the total
}
int main() {
// Define an array of numbers
int numbers[] = {5, 10, 15, 20, 25};
int size = sizeof(numbers) / sizeof(numbers[0]);
// Calculate total via function
int totalSum = sumArray(numbers, size);
// Display result
cout << "The sum of the array elements is: " << totalSum << endl;
return 0;
}