Member Avatar for Raim

I am trying to make the following program.

SUM=1+1/2+1/3+1/4+1/5....1/n

n should be input by the programmer.

I thought that using

for

would work, but it only gives me a series of
1+1
1+2
1+3,etc.

What I wish to get is the series itself and the total addition of it. Any help please?

Recommended Answers

All 5 Replies

To do this you need a sum variable that you will add to ever iteration. Then in your for loop all you have to do is add the part to the total.

double sum = 0;
for (int i = 0; i < n; i++)
{
    sum += //calc to get part
}
cout << sum;
Member Avatar for Raim

Thanks, that sure helped me. The code is here for anyone that might want to take a look at it:

int n;
	double sum = 0;
	//promt user to enter the number.
	cin>>n;
    for (int i = 0; i<=n; i++)
    {
    sum+=i;
    }
	cout<<sum <<endl; //demonstrating the result

You do know that what you have coded will not give you sum of 1+1/2+1/3+...+1/n

Thanks, that sure helped me. The code is here for anyone that might want to take a look at it:

int n;
	double sum = 0;
	//promt user to enter the number.
	cin>>n;
    for (int i = 0; i<=n; i++)
    {
    sum+=i;
    }
	cout<<sum <<endl; //demonstrating the result

This gives you the sum of 0 + 1 + 2 + ... + n

You want the sum of 1/1 + 1/2 + 1/3 + ... + 1/n

So instead of each term being i, you need it to be its inverse.

Member Avatar for Raim

The 0 in the for was a mistake of me. A typo, I thought I had typed a 1. And while the problem itself was asking 1/1+1/2, I left it at 1+2+3 because it was basically the same itself. Thanks anyways, program solved.

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.