C++ program to calculate the sum of all elements in an array:
Code:
#include <iostream>
using namespace std;
int main() {
// Declare an array
int arr[] = {1, 2, 3, 4, 5};
// Calculate the length of the array
int length = sizeof(arr) / sizeof(arr[0]);
// Initialize sum
int sum = 0;
// Loop through the array and calculate the sum
for (int i = 0; i < length; ++i) {
sum += arr[i];
}
// Display the sum
cout << "Sum of all elements in the array: " << sum << endl;
return 0;
}
Output:
Sum of all elements in the array: 15
Time Complexity: O(n)