So I have an assignment to write a program that calculates and prints the sum of the series for the following series:
S = 1/(1*2) + 1/(2*3) + 1/(3*4) + ... + 1/(n*(n+1))

I know I basically need to loop and increment a variable till it equals n, but I don't know what I'm doing wrong in my code

//Program to calculate and print the sum of a series

#include <iostream>
using namespace std;
int main ()
{
	//declare variables
	int n;	//input variable
	int x(1);
	double term(0);
	double sum(0);		//sum of series

	//prompt user
	cout << "Please enter the value of n in the series of form sum=sigma(1/(n)*(n+1)): ";

	//accept input
	cin >> n;

	//calulate series using loops

	while (x<=n)
	{
		term += 1/(x*(x+1));
		sum += term;
		x++;

	}

	cout << "The sum of the series is " << sum <<endl;
return 0;
}

Please help!

You are going to have a problem in this line:

term += 1/(x*(x+1));

You have declared x as an integer. x * (x + 1) is going to be greater than 1. Let's say x is 2.

(x * (x + 1)) = (2 * (2 + 1)) = 6.

In C++,

1/6 = 0, not 0.1666666667

You are dealing with integer division, which truncates. You need to typecast 1 to a double:

term += 1.0 / (x*(x+1));

This will result in a double, so you won't just be adding 0.

That makes a lot more sense...thank you! I'll try that once I can get back in the comp lab.

term += 1/(x*(x+1));
or
term = 1/(x*(x+1));
?

no, it's += because I'm adding the past term to next.

term += statement is the same thing as term = term + statement

But I did finally solve it! Def thanks in part to VernonDozier

//Program to calculate and print the sum of a series

#include <iostream>
using namespace std;
int main ()
{
	//declare variables
	int n;	//input variable
	int x(1);
	double term(0);

	//prompt user
	cout << "Please enter the value of n in the series of form sum = sigma(1/(n)*(n+1)): ";

	//accept input
	cin >> n;

	//calulate series using loops

	while (x<=n)
	{

		term += 1.0/(x*(x+1));
	
		x++;

	}

	cout << "The sum of the series is " << term <<endl;
return 0;
}

if anyone was curious.

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.