Help with program

Hello,

I'm trying to create a program that will do the following:
The user puts in however many integers he or she wants.
When the user presses enter, the program will calculate the sum, the median value and the largest and the next to the largest integer entered.

Example output:
Enter your numbers : 10 12 -5 20 -2 15
Sum = 50
Median value. = 8.3
Largest = 20
Second to the largest =15

So far I've been having to rely on youtube for solving my assignments, but this one I just havent been able to crack.

I really appreciate any help I can get!

Thank you.
1
2
3
4
5
6
7
#include <iostream>
int main(){
   int n;
   while(std::cin>>n){
      //...
   }
}
The median for your example ( 10 12 -5 20 -2 15 ) should be 11, not 8.3 as far as I know since the average of 10 and 12 is 11.

I was not able to come up with a way to just enter however many values and make the program output the results. I needed to include some sort of a flag to indicate the end of input (other than pressing Control + z in Windows CMD ). In my program, 'e' signals the end of input.
1
2
3
4
5
6
7
8
Enter your numbers followed by 'e': 10 12 -5 20 -2 15 e
Sum = 50
Median = 11
Largest = 20
Second Largest = 15

Process returned 0 (0x0)   execution time : 16.046 s
Press any key to continue.


If you are only looking for the sum, then I can probably allow the user to just enter however many numbers only and produce the result, but finding the median, largest and secondToLargest requires an array/vector and it requires the user to let the program know where the "end" is.

If you are happy with what I did and you want to know how I did it, let me know and I will help. If not, someone else might know a way to accomplish the task better.
Last edited on
> but finding the median, largest and secondToLargest requires an array/vector
only the median.
1
2
3
4
5
6
7
std::vector<int> v;
int n;
while(std::cin>>n){
   v.push_back(n);
   //...
}
std::sort(v.begin(), v.end()); //for the median 


largest and secondToLargest only need two variables.


> other than pressing Control + z in Windows CMD
that's the idea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main()
{
    std::vector<int> values;

    std::string line;
    std::cout << "Enter your numbers:\n> ";
    getline(std::cin, line);

    std::istringstream iss(line);
    int value;
    while (iss >> value)
        values.push_back(value);

    // in lieu of doing the actual work:
    for (auto val : values)
        std::cout << val << '\n';
}
@cire
Nice. Thanks for that idea. Using getline () and string stream works. It eliminates the need for signaling end of input by the user.

1
2
3
4
5
6
7
8
Enter your numbers: 1 3 -4 6 20 4 67 8
Sum = 105
Median = 5
Largest = 67
Second Largest = 20

Process returned 0 (0x0)   execution time : 9.310 s
Press any key to continue.
Last edited on
Topic archived. No new replies allowed.