943,923 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2697
  • C++ RSS
Dec 2nd, 2008
0

Average Program using an Array

Expand Post »
How do I code a C++ program that used an array to find an average of positive numbers. Then outputs the result
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
csaund1 is offline Offline
6 posts
since Sep 2008
Dec 2nd, 2008
0

Re: Average Program using an Array

sum them all up and divide by the size of the array. For example
C++ Syntax (Toggle Plain Text)
  1. int a[3] = {2,4,6};
  2.  
  3. The sum is 2+4+6 = 12
  4. The average is 12/3 = 4
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,953 posts
since Aug 2005
Dec 2nd, 2008
0

Re: Average Program using an Array

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
Reputation Points: 12
Solved Threads: 0
Light Poster
Ψmon is offline Offline
30 posts
since Mar 2007
Dec 3rd, 2008
0

Re: Average Program using an Array

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.
Reputation Points: 749
Solved Threads: 134
Practically a Master Poster
StuXYZ is offline Offline
660 posts
since Nov 2008
Dec 3rd, 2008
0

Re: Average Program using an Array

C++ Syntax (Toggle Plain Text)
  1. define total = 0
  2. define array[n] = {n1, n2, n3, n4, ...}
  3. for 0 to n - 1
  4. total = total + array[n]
  5. print 'Average: '
  6. print total / n
  7. end
Reputation Points: 92
Solved Threads: 16
Junior Poster
chococrack is offline Offline
149 posts
since Oct 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Simple Craps Game
Next Thread in C++ Forum Timeline: Array Question





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC