Below Average output

Hello everyone!

Im pretty new to c++ and was hoping on some suggestions. I'm working on a program now that ask for weights, totals the weights, averages the weights and than displays the weights that are less than average.

I was able to get everything to display besides the last part where it displays the weights below average.

I was hoping I can accomplish this without completely changing my code, any suggestions would be awesome!

Thanks in advance!


OUTPUT:
Enter a weight (0 to stop): 1
Enter a weight (0 to stop): 2
Enter a weight (0 to stop): 3
Enter a weight (0 to stop): 4
Enter a weight (0 to stop): 5
Enter a weight (0 to stop): 6
Enter a weight (0 to stop): 7
Enter a weight (0 to stop): 8
Enter a weight (0 to stop): 9
Enter a weight (0 to stop): 10
Enter a weight (0 to stop): 0
The total was 55
The average is 5.5
Here are all the numbers less than the average:


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
  #include <iostream>
#include <string>
using namespace std;

int main(){
 int w;
 float t=0;
 int count=0;
   while (w!=0){
      cout<<"Enter a weight (0 to stop): ";
      cin>>w;
      cout<<w<<endl;
    if (w!=0){
       count = count +1;
       t=t+w;
    }
   }
   cout<<"The total was "<<t<<endl;
   float a= t/count;
   cout<<"The average is "<<a<<endl;
   
   
   cout<<"Here are all the numbers less than the average:"<<endl;

  

         return 0;
         }
The problem you face is that when you know the average your program has forgotten all the numbers so you can't display anything.
To solve this you can store the numbers in a vector. After you know the average you can display the numbers that are below.
@thomas1965
is a vector similar to an array?
Last edited on
Vector is kinda like an array, but I prefer using vectors, because you can give it a size from user, delete and add elements, more useful than array I think
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
int w;
float t = 0;
int count = 0;
vector<int> belowavg;
do {
cout << "Enter a weight (0 to stop): ";
cin >> w;
if (w != 0) {
belowavg.push_back(w);
}
cout << w << endl;
if (w != 0) {
count = count + 1;
t = t + w;
}
} while (w != 0);
cout << "The total was " << t << endl;
float a = t / count;
cout << "The average is " << a << endl;

cout << "Here are all the numbers less than the average:" << endl;

for (int i = 0; i < belowavg.size(); i++) {
if (belowavg[i] < a) {
cout << belowavg[i] << " ";
}
}

cout << endl;
system("pause");

return 0;
}

this is the code using vector
I agree with nick2361. std::vector is much more powerful than array.
Topic archived. No new replies allowed.