Gold University of Minnesota M. Skip to main content.University of Minnesota. Home page.
 
 
 

What's inside.

Ta Email

Download Compiler

Final Project

Lab Notes

Office Hours

Schedule

Syllabus

Announcements

Check Grades

 

CSci 1113 Home

 
 

Printer-friendly version

 
Calculate PI from a Series Expansion Using a for Loop

% cat pi.cpp
// calculate pi from a series
# include <iostream>
# include <iomanip>
using namespace std;

int main()
{
  double sum, denom, sign;
  int n;

  // input data

  do
  {
     cout << "Enter the number of terms (must be greater than zero): " << endl;
     cin >> n;
  } while( n <= 0 );

  // initialize variables

  sum = 0.0;
  denom = 1.0;
  sign = 1.0;

  // calculate pi using a for loop

  for (int i=1; i <= n; i++ )
  {
      // cout << "sign = " << sign << " denom = " << denom
      // << endl; // diagnostic

      sum += sign * 4.0 / denom;

      denom += 2.0;
      sign = sign * (-1.0);

  }

  // output the result

  cout.setf(ios::fixed);
  cout.setf(ios::showpoint);
  cout.precision(4);

  cout << "The value of pi from the first "<< n
       << " terms of the series is " << sum << endl;

}
 

% g++ pi.cpp
% a.out
Enter the number of terms (must be greater than zero):
10
The value of pi from the first 10 terms of the series is 3.0418
% a.out
Enter the number of terms (must be greater than zero):
10000
The value of pi from the first 10000 terms of the series is 3.1415

 
The University of Minnesota is an equal opportunity educator and employer.
CSci 1113: C++ Programming