# Thread: how to find a sum of series in java

1. Member
Join Date
Oct 2014
Posts
20
Rep Power
0

## how to find a sum of series in java

Can someone explain to me how to find the sum of the following series
f(x)= 1+3+5+.......+2n+1
this what I did
Java Code:
```for ( n=0;x>0 && x<2*n+1;n++)
{
sum=sum+2*n+1;
n++;
System.out.println(sum);```
Is it infinite loop?
is this correct ? it was in my exam and I think I massed up everything!

2. Senior Member
Join Date
Jan 2013
Location
Northern Virginia, United States
Posts
6,226
Rep Power
13

## Re: how to find a sum of series in java

First, it normally goes to 2n - 1 so if n = 1 the first term is 1.
It is well known that the sum of an arithmetic series of odd numbers
starting with 1 is a square so you could just use:

sum = n*n; // for any number of n odd terms.

In any event you probably got a compiler error because x is not defined anywhere.

Regards,
Jim
Last edited by jim829; 11-02-2014 at 02:56 PM. Reason: grammar and spelling and a bit more clarification

3. Senior Member
Join Date
Apr 2013
Location
Sweden
Posts
272
Rep Power
7

## Re: how to find a sum of series in java

Also, if you are faced with any arithmetic progression, you can use the formula:

(n(2a + (n - 1) d)) / 2

where a is the first term, d is the common difference, and n is the number of terms you wish to sum.

of course in this case, as mentioned, your series is n^2.

4. Member
Join Date
Oct 2014
Posts
20
Rep Power
0

## Re: how to find a sum of series in java

Originally Posted by jim829
First, it normally goes to 2n - 1 so if n = 1 the first term is 1.
It is well known that the sum of an arithmetic series of odd numbers
starting with 1 is a square so you could just use:

sum = n*n; // for any number of n odd terms.

In any event you probably got a compiler error because x is not defined anywhere.

Regards,
Jim
I didn't get it why is the sum=n*n
is this what u meant
Java Code:
```public class Review{
public static void main(String[] args){
int x=1,n=0,sum=0;
for (n=0;x<=2*n+1 ; n++)
{
sum=sum+n*n;

}

System.out.println("sum ="+ sum);

}
}```
out put
sum= 1610612736
last question is this infinite loop?

Thank you
Last edited by skj; 11-04-2014 at 05:26 PM.

5. ## Re: how to find a sum of series in java

The sum of the series is a square because:

Java Code:
```13579
33579
55579
77779
99999```
I guess you can see the regularity ...

kind regards,

Jos

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•