Allocating an array at runtime - C++ Statement

C++ examples for Statement:while

Description

Allocating an array at runtime

Demo Code

#include <iostream>

int main() {/*from ww  w  .ja v a2  s.  c  om*/
  const int count{5};
  unsigned int height[count];                 // Create the array of count elements

                        // Read the heights
  int entered{};
  while (entered < count)
  {
    std::cout << "Enter a height: ";
    std::cin >> height[entered];
    if (height[entered])                     // Make sure value is positive
    {
      ++entered;
    }
    else
    {
      std::cout << "A height must be positive - try again.\n";
    }
  }

  // Calculate the sum of the heights
  unsigned int total{};
  for (int i{}; i<count; ++i)
  {
    total += height[i];
  }
  std::cout << "The average height is " << total / count << std::endl;
}

Result


Related Tutorials