# Number Series Program Code Help

Page 1 of 1

## 2 Replies - 1529 Views - Last Post: 19 October 2010 - 07:09 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=195813&amp;s=80e39dca76292c767a3c096a494040e9&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 MoMahar26

Reputation: 1
• Posts: 13
• Joined: 13-January 10

# Number Series Program Code Help

Posted 19 October 2010 - 06:18 PM

I am very close to finishing this, but I think I have some sort of problem with my calculations, as my output is incorrect.
Here is the problem statement:
Write a JAVA program using while loops to calculate and display the total of the following series:
1/30 + 2/29 + 3/28 + ... + 30/1

Here is what I have so far:

```        double sum=0;

int num=1;
while(num<=30)
{//begin of outer while loop
int den=30;
while(den>=1)
{//begin of inner while loop
sum+=(double)(num/den);
den--;
}//end of inner while loop
num++;
}//end of outer while loop
System.out.println("The sum is "+sum);
```

With this code, the output I am getting is:

run:

The sum is 1492.0
BUILD SUCCESSFUL (total time: 0 seconds)

The output is supposed to be: 93.84460106

Any help would be appreciated. Please keep in mind that I am a beginner.

Thank You!

My apologies, disregard. I meant to post this in JAVA.

Pay no attention to that bottom line, I accidentally posted this first in the VB.net forum, and just copied and pasted the original in here.

Is This A Good Question/Topic? 0

## Replies To: Number Series Program Code Help

### #2 Dogstopper

Reputation: 2914
• Posts: 11,169
• Joined: 15-July 08

## Re: Number Series Program Code Help

Posted 19 October 2010 - 07:07 PM

You only need one loop. Notice the pattern? The number on the bottom is 31 minus the number on top. Also note that if you divide two integers, you are performing int division, which you tried to avoid unsuccessfully. You have sum+=(double)(num/den); You need to convert either the numerator or denominator first, otherwise, it will perform the division first, THEN convert to a double. So, you can do that with your code:

```
double sum=0;

int num=1;
while(num<=30)
{
int den= 31 - num;
sum += ((double)num)/den;

num++;
}
System.out.println("The sum is "+sum);

```

Note that I have not tested this code, but should be giving you an accurate answer if I have done it right.

### #3 Luckless

• </luck>

Reputation: 293
• Posts: 1,146
• Joined: 31-August 09

## Re: Number Series Program Code Help

Posted 19 October 2010 - 07:09 PM

real simple mistake actually. make num and dem doubles instead of ints and it works fine. The error in math is an accumulation of integer divisions (basically int rounding. Happy to help good job