could anybody tell me how to sum the sequence given using loops instead of using any other function of c++?

1 + 1/1! + 1/2! + 1/3! + .....1/n!

Recommended Answers

All 2 Replies

You first need to write a function that returns the factorial of a number. Be careful here because those values will grow very large very quickly. Calculating factorials in c++ programs has lots of limitations due to small numeric sizes. See limits.h for the maximum size of an integer or other numeric variables.

Once you have that, the rest should be pretty easy.

There is a simple solution in that case:

const int N = 100;
const double eps = 1e-16;
// 1 + 1/1! + 1/2! + 1/3! + .....1/n!
void Eseries()
{
    double y = 1.0;
    double f = 1.0;
    double x = 1.0;

    for (int i = 0; i < N; ++i, y += 1.0)
    {
        f /= y;
        if (f < eps)
        {
            cout << "break " << i << " eps " << f << endl;
            break;
        }
        x += f;
    }
    cout << setprecision(16) << x << endl; 
}

No sense to calculate the e number if 1/n! < 1e-16 (n = 18, for double precision ~16 decimal digits).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.