Help asap please!


Urgent I have an assignment, i think the error is in passing the counter, the question is that i should pass it as reference, it doesnt output the number of counts it output the counter place at the memory, so how to pass it as reference and show out the counts?
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
  
  int countHowMany(int n, int arr[], float avg, int& counter)
  {
    counter=0;
    
    for(int i=0; i<n; i++)
    {
       if(arr[i]>=avg)
          counter=1;
       else
          counter=2;
    }
    return counter;
   }
   
   void engine()
   {
     int n, arr[max], counter, count1, count2;
     float avg;

     countHowMany(n, arr, avg, counter);
     if(counter==1)
        count1++;
     else
        count2++;
     
     cout<<"There are "<<count1<<" above or equal to average."<<endl;
     cout<<"There are "<<count2<<" below the average." 
    }
Last edited on
Your countHowMany sets the counter to either value 1 or value 2. Furthermore, the value of the counter is entirely determined by the value of the last element of the array. You could simplify your function to this and still get exactly the same result:
1
2
3
4
5
6
7
8
void countHowMany( int n, const int arr[], float avg, int & counter ) {
  if ( n < 1 )
    counter = 0;
  else if ( arr[n-1] >= avg )
          counter=1;
  else
          counter=2;
}

That, obviously is not what you want to do.

Your engine adds exactly 1 either to count1 or to count2, depending on the value of that last element.

Perhaps you should count only the elements that are equal or above the average?

How much should count1+count2 be, logically?
Thanks alot but it seems that you didnt get my point, the counter should count how many number above the average and how many less, and pass it to the other function and cout it there..
Last edited on
You cannot have one number that holds two values simultaneously.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int countHowMany(int n, int arr[], float avg)  
	{
		int counter = 0;

		for (int i = 0; i<n; i++)
		{
			if (arr[i] >= avg)					
				counter++;							
		}
		return counter;
	}

	void engine()
	{
		int n, arr[max], aboveEqualToAvg, belowAvg;
		float avg;

		aboveEqualToAvg = countHowMany(n, arr, avg);
		
		belowAvg = (max - aboveEqualToAvg);

		cout << "There are " << aboveEqualToAvg << " above or equal to average." << endl;
		cout << "There are " << belowAvg << " below the average.";
	}


If the array entry is above the avg value (which you will need to initialize with a value) counter will increment by 1. Counter will be passed to main and assigned to aboveEqualToAvg. I am assuming that max is constant defined elsewhere. You calculate the the number of entries by subtracting aboveEqualToAvg from max.
Thank you so much all appreciate it.. And i solved it
Topic archived. No new replies allowed.