// // unnecessaryNesting2.cpp
// Series approximations to pi, using formula:
//
// 4 4 4 4 4 4
// pi = - - - + - - - + - - -- + ...
// 1 3 5 7 9 11
//
// Calculates the first 1,000,001 approximations.
// Displays only select approximations.
#include <iostream>
#include <iomanip>
int main()
{
const int COLUMN_WIDTH = 7;
// Display table headings:
cout << endl;
cout << "pi series approximations" << endl;
cout << "------------------------" << endl << endl;
cout << " n Sum to nth term" << endl;
cout << "------- ---------------" << endl << endl;
// Display table body:
double sum = 0;
int powerOfTen = 1;
int digitCount = 1;
for ( int n = 0; n <= 1000000; n++ ) {
// Calculate nth term and add to series:
int termDenominator = 1;
for ( int i = 0; i < n; i++ )
termDenominator += 2;
double term = 4.0 / termDenominator;
if ( n % 2 == 1 )
term = term * -1;
sum = sum + term;
// Display row of table if n is a power of 10:
// with right-justified left column:
if ( n == powerOfTen ) {
cout << setw(COLUMN_WIDTH) << n
<< " " << sum << endl;
powerOfTen = powerOfTen * 10;
} // if
} // for n
return 0;
} // function main