Read n, then n numbers into an array made with new int[n]. Print their sum and the largest one, then release the array with delete[].
What to build
A program that stores numbers in an array made with new and releases it afterwards.
Requirements
- Allocate exactly
nints withnew int[n]. - Find the sum and the largest number.
- Release the array with
delete[].
Input
The first line has n (1 ≤ n ≤ 1000). The second line has the n numbers (each from -1,000,000 to 1,000,000).
Output
sum S max M
Constraints
1 ≤ n ≤ 1000, and each number is from -1,000,000 to 1,000,000.
Example
Input:
4
3 9 -2 5
Output:
sum 15 max 9
Why it works
new int[n] makes an array whose size is known only while the program runs. Memory from new[] must be released with delete[], or it leaks.
Examples
Example 1 · Input
4 3 9 -2 5
Expected output
sum 15 max 9
Example 2 · Input
1 -7
Expected output
sum -7 max -7
Hints
Hint 1
int* a = new int[n]; makes room for n numbers.
Hint 2
Read them, find the sum and the largest, then release the memory with delete[] a;
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int* a = new int[n];
for (int i = 0; i < n; i++) cin >> a[i];
long long sum = 0;
int best = a[0];
for (int i = 0; i < n; i++) {
sum += a[i];
if (a[i] > best) best = a[i];
}
cout << "sum " << sum << " max " << best << endl;
delete[] a;
return 0;
}