DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Average Program using an Array (http://www.daniweb.com/forums/thread160431.html)

csaund1 Dec 2nd, 2008 12:26 pm
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

Ancient Dragon Dec 2nd, 2008 12:36 pm
Re: Average Program using an Array
 
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

Ψmon Dec 2nd, 2008 1:13 pm
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

StuXYZ Dec 3rd, 2008 10:48 am
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.

chococrack Dec 3rd, 2008 11:42 am
Re: Average Program using an Array
 
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


All times are GMT -4. The time now is 4:27 pm.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC