Sum of Numbers!


Hello everyone,

I'm trying to solve this problem but I need your help with it

Write a program to sum the following series:
1/3 + 3/5 + 5/7 + 7/9 + 11/13 + ... + 95/97 + 97/99

I searched for 2 days to find any way to make the code work, but without any good result.

Can you help me please.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

int main()
{
	int i;
	int n;
	float sum=0;


	for(i=1,n=i+2;i<100&&n<=100; i++,n++)

		//cout << i/n;
		sum += (i/n);

	cout<<"Sum = "<<sum;


	return 0;
}
Your numerator (i) and your denominator (n) should increment by 2 each time, not one.

Also, you don't need to test if (i<100) since (i<n) at each step. Just test n.

Finally, on line 14, you are making a classic, non-obvious mistake. i/n is an integer value, since both i and n are integers. You must cast at least one of them to a float:

sum += (float)i/n;

Hope this helps.
Hello Duoas,
Thank you for your reply,

I tried to apply your notes on my code, but when I ran the compiler it shows me a black screen only!
Can you please review my new code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
using namespace std;

int main()
{
	int i;
	int n;
	float sum=0;


	for(i=1,n=i+2;i<n&&n<=100; i+2,n+2)

		//cout << i/n;
		sum += (float)i/n;

	cout<<"Sum = "<<sum;


	return 0;
}


Thank you again :)
Edit: Did not mean to sound harsh sorry lol :p

I also misread the for-loop. Look below.
Last edited on
That's a pretty harsh way of saying it.

n++ changes n exactly the same as n=n+1 would, or even shorter: n+=1.

n+2 does not change n. It should be n+=2.

Hope this helps.
hahaha before I logged in here I was reading as TraikNeaj advised me, and I found the error as Duoas explain !!
Sometimes you need a harsh words to convinced yourself to look deeper, and as a result, here is the final code for anyone will search for the same problem ;)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
using namespace std;

int main()
{
	int i;
	int n;
	float sum=0;


	for(i=1,n=i+2;i<n&&n<=100; i+=2,n+=2)

		sum += (float)i/n;

	cout<<"Sum = "<<sum;


	return 0;
}


Thank you very much for your tips and review, Duoas.
Also thank you Tarik
Topic archived. No new replies allowed.