Max/Min, is there a better way I can do this?

Below is the program I came up with, it is supposed to max/min/average 6 user-entered numbers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;

int main()
{
    double maxVal = 0,
           minVal = 0,
           average = 0.0,
           finalVal = 6,
           test = 0,
           counter,
           num = 0;

    cout<<"Enter six numbers: ";
    cin>>num;

    maxVal = num;
    minVal = num;
    average+=num;

    for(counter = 1; counter < finalVal; counter++)
    {
        cout<<": ";
        cin>>num;
        if(num < minVal)
        {
            minVal = num;
        }
        if(num > maxVal)
        {
            maxVal = num;
        }
        average+=num;

        }

    average/=finalVal;

    cout<<"\nMax Value is: "<<maxVal;
    cout<<"\nMininum Value is: "<<minVal;
    cout<<"\nAverage is: "<<average;

    return 0;
}


I just want to know if there is anything amateurish about it, something that can be done better or less "messy" using ONLY if and loops, currently my class is in the "if" and "loop" chapters so I can't really use very advanced things (if there are any applicable).

In fact the program is fine.
As for me I would write it the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>

int main()
{
    const unsigned int TOTAL_NUMBERS = 6;
    double maxVal, minVal, average;


    std::cout << "Enter " << TOTAL_NUMBERS << " numbers\n";

    for ( unsigned int i = 0; i < TOTAL_NUMBERS; i++ )
    {
        std::cout << i + 1 << "> ";

        double num;
        std::cin >> num;

        if ( i == 0 )
        {
            minVal = maxVal = average = num;
        }
        else
        {
            average += num;
            if ( num < minVal )
            { 
                minVal = num;
            } 
            else if ( maxVal < num )
            {
                maxVal = num;
            }
        }
    }  

    average /= TOTAL_NUMBERS;

    std::cout << "\nMax Value is: " << maxVal;
    std::cout <<"\nMininum Value is: " << minVal;
    std::cout << "\nAverage is: " << average;

    return 0;
}

Last edited on
Topic archived. No new replies allowed.