# summation in java using for loops

• 03-16-2011, 04:44 PM
java157
summation in java using for loops
I am trying to make a summation calculator for the following equation:

http://i595.photobucket.com/albums/t...60/sinesum.jpg

Where i is the lower limit (in this case it will always be 0) and n is the upper limit (in this problem the user will be asked to enter an integer value of the upper limit).

Here is my code (so far):

import java.io.*;
public class summation
{
public static void main(String args[]) throws IOException
{

int ul;

System.out.print("Enter the upper limit: ");

}

}

I don't understand how to use a for loop to calculate the sum.

After that I got stuck. I appreciate any help i can get thanks! :)
• 03-16-2011, 04:52 PM
JosAH
Quote:

Originally Posted by java157
I am trying to make a summation calculator for the following equation:

http://i595.photobucket.com/albums/t...60/sinesum.jpg

Are you sure that summation is correct? There is no dependency on i in the term to be summed so the entire thing can be reduced to (n+1)*T where T is that term.

kind regards,

Jos
• 03-16-2011, 05:52 PM
ozzyman
You will need some math functions.

Math.pow returns the value of the first argument raised to the power of the second argument.
Code:

`double Math.pow(double a, double b)`

To calculate the factorial make your own loop e.g.
Code:

```private int factorial(int number) {     int counter = number;     int answer = counter;     while (counter > 1) {       answer *= --counter;     }     return answer; }```

And then make a for-loop over your entire equation with your limits put in e.g.
Code:

```double totalSum = 0; double sum = 0; for (i=0; i<=n; i++) {   ...   totalSum += sum; } return totalSum;```

But beware whereever you add an integer to the sum, convert it to a double first, or cast it to a double.
• 03-17-2011, 09:33 AM
DavidG24