
-----------------------------------
omni
Wed Nov 10, 2004 6:10 pm

Help on dynamic arrays
-----------------------------------
I want to make a program that will just calculate an average of numbers. It will receive input from a file. I want my program to be able to accept a variable amount of numbers. 
I'm thinking of using dynamic memory for this. 

(pseudocode)
Open file stream
create array
set SUM=0
set COUNTER=0
Loop
 receive input from file
 move input into array
 SUM=SUM + input from the array
increase counter
 allocate more memory for the next number
end loop
AVERAGE=SUM / COUNTER
(END)

Is this logic right ?

-----------------------------------
wtd
Wed Nov 10, 2004 6:11 pm


-----------------------------------
Storing the numbers in an array would be more flexible, but isn't necessary for this problem.

Each time you read a number, add it to a total, then increment a counter by 1.  At the end, divide the total by the counter.

-----------------------------------
omni
Wed Nov 10, 2004 7:28 pm


-----------------------------------
LMAO, thank you wtd. I don't know what I was thinking.
What if I want to keep the numbers in the array for later use?

-----------------------------------
wtd
Wed Nov 10, 2004 7:53 pm


-----------------------------------
If we're talking about C++, then don't use arrays.  Instead, use a vector.

#include 
#include 

int main()
{
   std::vector input_numbers;
   bool cont(true);
   int total(0);

   while (cont)
   {
      int input;
      char response('n');
      std::cin >> input;
      input_numbers.push_back(input);
      std::cout  response;
      cont = response == 'y' || response == 'Y';
   }

   for (std::vector::iterator iter(input_numbers.begin()); iter != input_numbers.end(); iter++)
   {
      total += *iter;
   }

   int average(total / input_numbers.size());

   std::cout > input;
      input_numbers.push_back(input);
      std::cout  response;
      cont = response == 'y' || response == 'Y';
   }

   std::cout 