What did you do in the array version? Was it:
1. Read the numbers one by one and tally up the sum.
2. Compute average
3. Look through the numbers again and tally up the count. |
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
|
#include<iostream>
using std::cin;
using std::cout;
void foo( int i )
{
if ( 0 < i )
{
int num;
cout<<"\nEnter an integer value:";
cin >> num;
foo( i - 1 );
cout << "Pos " << i << " was " << num << '\n';
}
return;
}
int main()
{
int k;
cout<<"Enter how many numbers you want to enter:";
cin>>k;
foo( k );
return 0;
}
|
The
foo is recursive. It has the end condition on line 7 to prevent infinite recursion.
Each call reads one number and leaves the rest for the recursive call.
After those other calls have returned, it still remembers the value that it did read.
If k==4, there will be five function calls: foo(4), foo(3), foo(2), foo(1), and foo(0). Each has its own 'num' (except the foo(0) ).
The foo(0) basically just returns, but by that time all numbers have been read already. If you had been incrementing and passing a sum, you could calculate an average now.
Therefore, by the time these functions reach line 14, the average is known and can be used.
In your case you need to pass more information forth and back than foo() does.