Lab 1 - Dynamic Arrays

The purpose of this lab is to write a loop which dynamically allocates and deallocates an array of numbers.

For this lab, you will fill in main() for the following code snippet. Name your source code lab1.cpp. You may work in groups of no more than 2 students. Make sure BOTH of your names are in the comment section so that both of you will receive credit for the lab (if there are no names in the comment section at the top of the code, only the student that emails the assignment will receive credit).

// Your name:
// Your partner's name:
#include <iostream>
using namespace std;

// The allocateArray function given in lecture
int *allocateArray(int);

int main()
{
  int size;
  int *ptr = NULL;
  double sum = 0;

  // ************************************************************************
  // Fill in main() with the steps given in pseudocode below
  // ************************************************************************

  return 0;
}

int *allocateArray(int size)
{
  int *tmp;

  // Validate that size is greater than 0, even if already done in main()
  if(size < 1) return NULL;

  try {
    tmp = new int[size];
  } catch(bad_alloc) {
    tmp = NULL;
  }
  if(tmp == NULL) {
    cout << "Failed to allocate the array!\n";
  }

  // We don't need to exit(1) on allocation failure because tmp will be either
  // NULL or a valid address space. We can check in main if the function returns
  // NULL and continue on to the next iteration if it does.
  return tmp;
}
Note: to paste in vi on Sleipnir use the following last-line command before going into insert mode:
set :paste
Then exit insert mode (ESC) and give the following last-line command to re-enable automatic indenting:
set :nopaste
Your main() loop will be an infinite loop that calculates the average of a set of integers. The pseudocode for the loop is:
while true
  prompt the user for the number of integers (tell them to enter 0 to exit)
  read user's response into size variable
  if the size is 0, break out of the loop
  if the size is negative, continue to the next iteration of the loop
  call allocateArray(size) and assign its return value to ptr
  if ptr is NULL, continue to the next iteration of the loop
  have a for loop which asks the user for each integer (indices 0 to size-1)
    and also calculates the sum of the entered integers
  print the average to the screen (sum divided by size)
  deallocate the array
end-while
Do not forget to reset sum to 0 on each iteration.

Email lab1.cpp to me as an attachment. If you had a lab partner, you should also email your lab partner a copy.