954,157 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Average Program using an Array

How do I code a C++ program that used an array to find an average of positive numbers. Then outputs the result

csaund1
Newbie Poster
6 posts since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

sum them all up and divide by the size of the array. For example

int a[3] = {2,4,6};

The sum is 2+4+6 = 12
The average is 12/3 = 4
Ancient Dragon
Retired & Loving It
Team Colleague
30,043 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,341
 

What is not clear to me is: does the array have only positive numbers or are you finding the average of only positive numbers?

If the first, then Ancient Dragon has the con
If the second, you'd need to pull out only the positive numbers and divide by their count.

Perhaps ...
int a[6] = {2,-3, 4, -5, 6, -7};

int b[6] = new int[];
loop through a, placing positive values in b
then ...
The sum is 2+4+6 = 12
The average is 12/3 = 4

Ψmon
Light Poster
30 posts since Mar 2007
Reputation Points: 12
Solved Threads: 0
 

Think about how you add up. Suppose I ask you to add the
number in the series 2,6,9. you don't go let me put the numbers into
an array. you simply keep a running total,

So in your case

start a total
total=0
then IF the number is >0 add to total
divide total by the number of >0 numbers (or 42 ;-)

Just because it is programming it doesn't mean that you can forget you kindergarden maths.

StuXYZ
Practically a Master Poster
680 posts since Nov 2008
Reputation Points: 760
Solved Threads: 138
 
define total = 0
define array[n] = {n1, n2, n3, n4, ...}
for 0 to n - 1
    total = total + array[n]
print 'Average: '
print total / n
end
chococrack
Junior Poster
149 posts since Oct 2008
Reputation Points: 92
Solved Threads: 16
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You