Implementing an average counter for an array

AI Thread Summary
The discussion focuses on implementing a counter to calculate the average of an array and identify numbers less than and greater than or equal to that average. The user shares a code snippet that collects user input into an array until -1 is entered, counts the number of elements, and calculates the sum. The average is computed by dividing the sum by the number of elements. The user acknowledges that while there may be more efficient methods, the current approach is straightforward. The next step involves looping through the array to categorize the values based on their relation to the average.
clook
Messages
32
Reaction score
0
i need to get this array to calculate the numbers that are less than the average and greater than or equal to the average.

first of all, i need to figure out how to make a counter to count the average of the array! i can't find the code in the textbook

here's what i have so far:
Code:
#include <stdio.h>
#define MAXARR 20

main()
{
	int
		arr[MAXARR], i, counter, value, no_of_elements, max,sum;
    /*----------------------------------------------------------------------*/
    /* User is requested to enter values from keyboard until -1 is entered  */
    /*----------------------------------------------------------------------*/
    printf("\f");
	counter = 0;
	printf("Do not entere more than %d values\n\n",MAXARR);
	printf("Enter value (-1 to quit): ");
	scanf("%d", &value);
	while (value != -1)
	{
		arr[counter]=value;
		printf("Please enter value (-1 to quit):   ");
		scanf ("%d", value);
		counter = counter + 1;

	}

	/*----------------------------------------------------------------------*/
	/* Output routine.  The number of elements entered is displayed         */
	/*----------------------------------------------------------------------*/
    no_of_elements = counter;
	printf("%d values were entered\n",no_of_elements);
	printf("these values are: \n");
    for(i=0;i<no_of_elements;i=i+1)
		printf("%d  ",arr[i]);
 
Physics news on Phys.org
Code:
int sum=0;

for(int count=0; count<counter; count++)
{
   sum += arr[count];
}

double avg = sum/counter;

There's probably more efficient ways, but this is the easiest one I know of. From there, its a matter of another loop through the whole array and a simple if-else statement.
 

Similar threads

Replies
4
Views
1K
Replies
3
Views
1K
Replies
3
Views
1K
Replies
3
Views
1K
Replies
12
Views
2K
Replies
12
Views
2K
Replies
1
Views
10K
Replies
5
Views
2K
Back
Top