Storing numbers in a dynamic array, using new operator - C++ Operator

C++ examples for Operator:new

Description

Storing numbers in a dynamic array, using new operator

Demo Code

#include <iostream>
#include <cmath>

int main()//w  w  w .  j  a va 2 s.  c  om
{
  int n = 0 ;
  std::cout << "Enter the number of array elements: ";
  std::cin >> n;

  auto values = new (double[n]);

  for (int i = 0; i < n; ++i)
    *(values+i) = 1.0 / ((i + 1)*(i + 1));

  double sum {};

  for (int i {}; i < n; ++i)
    sum += *(values + i);

  std::cout << "result is " << std::sqrt(6.0*sum) << std::endl;

  delete[] values;                                              // Don't forget to free the memory!
}

Result


Related Tutorials