Group
Arrays and Vectors in C++
Objective
1. Define an array with several integer values.
2. Create a function that loops through the array to calculate the sum of its elements.
3. Return the total sum from the function.
4. Print the sum of the array elements.
5. Ensure that the program outputs the correct sum of all elements.
Calculate the sum of the elements of an array.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include iostream for input and output
using namespace std; // Use the standard namespace
// Function to calculate the sum of array elements
int sumArray(int arr[], int size) {
int sum = 0; // Initialize sum to 0
// Loop through the array to add each element to sum
for (int i = 0; i < size; i++) {
sum += arr[i]; // Add the current element to sum
}
return sum; // Return the total sum
}
// Function to print the elements of the array
void printArray(int arr[], int size) {
// Loop through the array and print each element
for (int i = 0; i < size; i++) {
cout << arr[i] << " "; // Print each number followed by a space
}
cout << endl; // Print a newline after the array
}
int main() {
// Define an array of numbers
int numbers[] = {5, 10, 15, 20, 25};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the size of the array
// Call the function to calculate the sum
int totalSum = sumArray(numbers, size);
// Print the sum of the array elements
cout << "The sum of the array elements is: " << totalSum << endl;
return 0; // End of program
}
Output
The sum of the array elements is: 75