Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a C++ program that approximates the value of the constant , based on both

ID: 3591445 • Letter: W

Question

Write a C++ program that approximates the value of the constant , based on both the Leibniz and the Wallis formulas for estimating . The formulas are shown in the images below:

The formulas work well for high values of n.

The program takes an input from the user for the value of n, which determines the number of terms in the approximation of the value of pi. The program then outputs that calculation for both formulas. You must also 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 by issuing an input of 0. The results must be shown to the 5th decimal place.

The program should print a string of text to the terminal before getting each piece of input from the user. A session should look like the following example (including whitespace and formatting), with various and different inputs and numbers in the output:

Note that each string printed by the program should include a newline at the end, but no other trailing whitespace (whitespace at the end of the line). Note that when the program exits, when a user enters 0, there is a newline generated.

2 1 5 3 1

Explanation / Answer

#include <iostream>

#include <iomanip>

//iomanip header need to be included to use setiosflags(ios::fixed) and setprecision(5) functions

using namespace std;

int main() {

//Variable declaration

int i,n=1;

float j,k;

double pi=0.00000;

//While loop to continue until user enter 0 as choice

while(n)

{

  

cout<<"Enter the number of terms to approximate (or zero to quit): ";

cin>>n;

//exit the loop and end the program if entered value is 0

if(n==0)

break;

//Implementation of Leibniz's formula

j=3.00000;

for(i=1,k=-1; i<=n; i++,k=k*(-1))

{

pi=pi+k*1/j;

j=j+2.00000;

  

}

pi=(1+pi)*4;

//Print the value of pi till 5th decimal point using std::cout << setiosflags(ios::fixed) << setprecision(5)

std::cout << setiosflags(ios::fixed) << setprecision(5) <<"The approximation for Leibniz's Formula is "<<pi<<" using "<<n<<" terms. ";

//Implementation of Wallis's formula

pi=1.00000;

j=1.00000;

for(i=1; i<=n; i++)

{

pi=pi*( ( (2*j)/((2*j)-1) ) * ( (2*j)/((2*j)+1) ));

j=j+1;

}

pi=pi*2;

//Print the value of pi till 5th decimal point using std::cout << setiosflags(ios::fixed) << setprecision(5)

std::cout << setiosflags(ios::fixed) << setprecision(5) <<"The approximation for Wallis's Formula is "<<pi<<" using "<<n<<" terms. "<<endl;

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote