C++ Exercise 30 defines the number e and Exercise 31 shows how to approximate the value of e using a different expression. Interestingly, the value of e can be approximated using the following expression: 2+1/1+1/2+2/3+3/4+4/5+5…/(n-1)+(n-1)/n+n Write a program that uses this formula to approximate the value of e. Test your program for n = 3, 5, 10, 50, and 100
Types of Loop
Loops are the elements of programming in which a part of code is repeated a particular number of times. Loop executes the series of statements many times till the conditional statement becomes false.
Loops
Any task which is repeated more than one time is called a loop. Basically, loops can be divided into three types as while, do-while and for loop. There are so many programming languages like C, C++, JAVA, PYTHON, and many more where looping statements can be used for repetitive execution.
While Loop
Loop is a feature in the programming language. It helps us to execute a set of instructions regularly. The block of code executes until some conditions provided within that Loop are true.
C++
Exercise 30 defines the number e and Exercise 31 shows how to approximate the value of e using a different expression. Interestingly, the value of e can be approximated using the following expression:
2+1/1+1/2+2/3+3/4+4/5+5…/(n-1)+(n-1)/n+n
Write a program that uses this formula to approximate the value of e. Test your program for n = 3, 5, 10, 50, and 100.
#include <iostream>
using namespace std;
float cal(int i, int n)
{
if(i == n)
return ((i-1) + (i-1)/(i+i));
static float sum = 2, j=0;
j += i + i/cal(i+1, n);
sum += 1/j;
return sum;
}
int main()
{
int n = 3;
float j = cal(1, n);
cout << n << " : " << j << endl;
n = 5;
j = cal(1, n);
cout << n << " : " << j << endl;
n = 10;
j = cal(1, n);
cout << n << " : " << j << endl;
n = 50;
j = cal(1, n);
cout << n << " : " << j << endl;
n = 100;
j = cal(1, n);
cout << n << " : " << j << endl;
return 0;
}
Trending now
This is a popular solution!
Step by step
Solved in 2 steps with 1 images