SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,julia Lobur
Chapter:
More Flow Of Control
Exercise:
Programming Projects
Question:12 | ISBN:9780321531346 | Edition: 7

Question

An approximate value of pi can be calculated using the series given below:

pi = 4 [ 1 − 1/3 + 1/5 − 1/7 + 1/9 ... + ((−1)n)/(2n+1) ]

Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation.Include a loop that allows the user to repeat this calculation for new values n until the user says she or he wants to end the program.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

​
#include<iostream>
#include<cmath>
using namespace std;
int main()
{   
 //variables
  double n;
  double pi=0;
  char repeatInput;
  int i,j,k=1;
  do
  { 
    //User input
    cout<<"Enter n value:";
    cin>>n;
    //Compute pi value
    for(i=1,j=2;i<n;i++,j++)
    {
       pi=pi+pow((-1),j)*4/k;
       k=k+2; 
    } 
    //Print output of pi value 
    cout<<"pi value:"<<pi<<endl;
    cout<<"Type 'y' to continue (or) Exit:";
    cin>>repeatInput;
  }while(repeatInput =='y' || repeatInput =='Y');
}

Output of code:

Enter n value:3.14
The approximation of the value of pi: 3.46667
Type 'y' to continue (or) Exit:y
Enter n value:15
The approximation of the value of pi: 3.73297
Type 'y' to continue (or) Exit:y
Enter n value:100
The approximation of the value of pi: 3.80036
Type 'y' to continue (or) Exit: Exit
0 0

Discussions

Post the discussion to improve the above solution.