LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Input/Output Programs · Question 1

Sum, average, minimum and maximum of n numbers in C++ Solution, output & explanation

  • Program
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

Read n and then n integers; print the sum, the average to two decimals, the smallest and the largest.

Solution
main.cpp
#include <algorithm>
#include <iomanip>
#include <iostream>

int main() {
    int n;
    std::cin >> n;
    int first;
    std::cin >> first;
    long long sum = first;
    int lo = first, hi = first;
    for (int i = 1; i < n; ++i) {
        int x;
        std::cin >> x;
        sum += x;
        lo = std::min(lo, x);
        hi = std::max(hi, x);
    }
    std::cout << "sum " << sum << ", average " << std::fixed << std::setprecision(2)
              << static_cast<double>(sum) / n << ", min " << lo << ", max " << hi << '\n';
    return 0;
}

Output Verified by compiling and running

sum 60, average 12.00, min -4, max 30

Starting min and max at the first value avoids special starting constants. The cast to double keeps the fraction of the average.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links