Problem solving !

Hey guys , so i have this homework for tomorrow to find the sum of numeric series of: "1/(2*3) + 4/(5*6) + 7/(8*9)............3*n-2 / (3n-1)*(3*n)"
I did this but im not sure if i have it done right or not , if its wrong please tell me another way of doing it..
p.s dont get it too complicated im a begginer thanks

#include <iostream>
using namespace std;
int main(){
double i,n,sum=0,k=2,l=3,h=1;
cout<<"Give the number n: \n";
cin>>n;
for (i=1;i<=(3*n-2)/(3*n-1)*(3*n);i++)
{
sum+=h/(k*i);
h=h+3;
k=k+3;
l=l+3;
}
cout<<"The sum of the numeric series is: "<<sum;
return 0;
}
Last edited on
you can probably solve it directly, but that is aside (spend some math time or google time to find out that the result = some f(x))

that aside,
I would do this just to avoid confusion:

for(i = 1; i < some_max; i+=3)
sum += i/((i+1)*(i+2));


it looks correct, its just a bit convoluted.
Last edited on
First, please use code tags when posting code. See http://www.cplusplus.com/articles/jEywvCM9/

Your code (and some whitespace) in tags:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main()
{
  double i, n, sum=0, k=2, l=3, h=1;
  cout << "Give the number n: \n";
  cin >> n;
  for ( i=1; i <= (3*n-2)/(3*n-1)*(3*n); i++ )
  {
    sum += h/(k*i);
    h = h+3;
    k = k+3;
    l = l+3;
  }
  cout << "The sum of the numeric series is: " << sum;
  return 0;
}


Okay, how many terms does the serie have?
Lets test:
On n==1, the last term is 1/(2*3). That is also the first term! One term in total.
On n==2, the last term is 4/(5*6). That is also the second term! Two terms in total.
Do you notice where this leads to?

There are n terms. Can you think of a much simple loop condition that gives you correct amount of terms?


Look at the equation on line 11. Is it an l or i in there? Which should it be?
Names of variables can be clear and descriptive, or mysterious and easy to typo.

You declare all variables in one statement. It is legal and compact, but can lead to errors.


You do use double values for everything. The division and sum do have to operate on floating point type (double), but the loop counter and h,k,l would be better as integers. Integers are exact, while floats are not always what we think them to be.

Have you seen:
1
2
3
int h=1,k=2,l=3;
double sum=0;
sum += static_cast<double>(h) / (k*l);

We convert the h into double value on the fly and that forces the entire division to use floating point math, but the h,k,l remain integers.

One could do the conversion differently:
1
2
3
4
5
6
7
int w;
double sum=0;

int z = 3*w;
int y = z-1;
double x = z-2
sum += x / (y*z);



What if the user gives 3.14 for n? How about -8? Or 0?
If n is integer, then the first won't be a problem; only the '3' is used.
The loop condition saves us from values <1, does it not?
Topic archived. No new replies allowed.