Choose either method 1 or method 2.

Don't use plagiarized sources. Get Your Custom Essay on

Question: Assignment 05 Write a C++ program (named Assignment05.cpp) that generate Pl to a user defined dec……

Get an essay WRITTEN FOR YOU, Plagiarism free, and by an EXPERT!

If method 1 is selected, delete lines 35-43

If method 2 is selected, delete lines 21-33

Both methods give same result.

OUTPUT :

CODE ;

#include <iostream>

#include <string>

using namespace std;

//This function takes an integer n and prints PI upto n decimal places

//For printing upto n decimal places,

// we can use pi as string and either print decimal characters iteratively(METHOD 1)

//or use substr function(METHOD 2)

void printPI(int n)

{

if(n<1 || n>16) //check if input lies between 1 and 16

{

cout<<“Invalid input n”;

return;

}

//store pi as a constant string. Store upto 18 decimal places

//we use string to prevent rounding off

const string pi = “3.141592653589793238”;

//METHOD 1:

//Choose either method 1 or method 2. Remove the other method

//print integer part

cout<<“Pi upto “<<n<<” decimal places = 3.”;

//print decimal part upto n decimal places, starting from pi[2]

//As pi[0] = ‘3’ and pi[1]=’.’

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

cout<<pi[1+i];

cout<<endl;

//===============Method 1 END=================

//METHOD 2 :

cout<<“Pi upto “<<n<<” decimal places = “;

cout<<pi.substr(0,n+2)<<endl;

//pi.substr(a,b) = returns substring of pi from index a .

// b represents length of substring

//since we need to print “3.” also, we add 2 to n and start from index 0 i.e (0,n+2)

//===============Method 2 END=================

}

int main()

{

int n;

cout << “Enter no. of decimal places : 1 to 16 : n”;

cin>>n;

printPI(n);

return 0;

}