How could this be done?

Hi

Below is a section of code that calculates the average of the input that is put into an array. Any number that is in the array is less than average, the code couts those numbers. But what if no number entered is less than average? How would this be written into the code? If there are no number less than average, it's suppose to cout "There aren't any!". I'm sure it's something easy and I always end up slapping myself on the forehead when I see it but can't figure this out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  average = sum/index;
           
           cout << "The total was " << sum << endl;
           cout << "The average is " << average << endl;
           cout << "Here are all the numbers less than the average: " << endl;
           int i = 0;
           while (i < index) {
                  if (array[i] >= average) {
			cout << "There aren't any!";
                  }
               if (array[i] < average) {
                   cout << array[i] << endl;
               }
               i++;
           }
Last edited on
Count how many numbers are less than the average. If the count is zero, output "There aren't any!"
Thanks for the reply. I'm in my first year of school I have a hard time visualizing the code and how it should look. I added something in, it seems to produced the needed verbiage but it repeats "There aren't any!" 5X.
Please don't edit your posts. This thread now makes no sense to anyone reading it.

You have added this:

1
2
3
      if (array[i] >= average) {
			cout << "There aren't any!";
                  }


So what is this doing? What does it check?

array[i] >= average

It checks to see if the element being looked at is larger than average. This is completely irrelevant. Here is how to count something in an array:

1
2
3
4
5
6
7
8
int count = 0;
for (int i = 0; i < size_of_the_array; ++i)
{
  if (SOME_CONDITION)
  {
      count++;
   }
}


I leave it to you to work out what SOME_CONDITION should be, based on the fact that you need to count how many elements are less than the average.

Count how many elements are below average. if the count is zero, output "There aren't any!"
Thanks. I know I didn't give the entire code but I added these lines in this way and now it works.

average = sum/index;

cout << "The total was " << sum << endl;
cout << "The average is " << average << endl;
cout << "Here are all the numbers less than the average: " << endl;
int i = 0;
int count = 0;
while (i < index) {
if (array[i] < average) {
count++;
cout << array[i] << endl;
}
i++;
}
if (count == 0) {
cout << "There aren't any!" << endl;
}
Topic archived. No new replies allowed.