Challenge: Add Up N Numbers
Completed
The first number n says how many numbers follow. Read those n numbers and print their sum and their largest value.
Input
First n (1 or more), then n integers.
Output
Sum: 18 Max: 9
Example
Input
3 4 9 5
Output
Sum: 18 Max: 9
Editor
C++
Hints
Loop n times and read one number each time.
Careful: the numbers can all be negative, so don't start the max at 0. Use the first number.
Solution explanation
The first number read becomes the starting maximum, so negative numbers work too.
Show solution
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
int biggest = 0;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
sum += x;
if (i == 0 || x > biggest) {
biggest = x;
}
}
cout << "Sum: " << sum << "\n";
cout << "Max: " << biggest << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module