C - Write program to create a double array with 100 elements

Requirements

Define an array, data, with 100 elements of type double.

Write a loop that will store the following sequence of values in corresponding elements of the array:

1/(2*3*4)  1/(4*5*6)  1/(6*7*8) ... up to 1/(200*201*202)

Write another loop that will calculate the following:

data[0] - data[1] + data[2] - data[3] + ... -data[99]

Multiply the result of this by 4.0, add 3.0, and output the final result.

Demo

#include <stdio.h>

int main(void)
{
  double data[100];                    // Stores data values
  double sum = 0.0;                    // Stores sum of terms
  double sign = 1.0;                   // Sign - flips between +1.0 and -1.0

  int j = 0;//from w  w w .j  a  v  a  2  s.  com
  for (size_t i = 0; i < sizeof(data) / sizeof(double); ++i)
  {
    j = 2 * (i + 1);
    data[i] = 1.0 / (j * (j + 1) * (j + 2));
    sum += sign * data[i];
    sign = -sign;
  }

  // Output the result
  printf("The result is %.4lf\n", 4.0*sum + 3.0);
  printf("The result is an approximation of pi, isn't that interesting?\n");
  return 0;
}

Result

Related Exercise