Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: calculate sum and product

1. ## calculate sum and product

The program is supposed to calculate the sum of number 1-5 and calculate the product of number 1-5. This is my code:

```package homeworktest;

/**
*
* @author user
*/
public class HomeworkTest {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int count = 0;
int sum = 0;
int product = 0;
do
{
count++;
sum += count;
product *= count;
if (count == 5)
System.out.println("Sum = " + sum);
System.out.println("Product = " + product);
} while (count < 5);
} //end main

}```
This is the output I get:
run:
Product = 0
Product = 0
Product = 0
Product = 0
Sum = 15
Product = 0

2. ## Re: calculate sum and product

I suggest writing down the math on a piece of paper, going through the algorithm the code executes a step at a time. As hint, 0 time anything will still be zero.

3. ## Re: calculate sum and product

Ugh, sorry, I still don't get it.

4. ## Re: calculate sum and product

`int product = 0;`
And later on:
`product *= count;`

0*1 = ?
0*2 = ?
0*3 = ?
...

5. ## Re: calculate sum and product

I hope you already have the answer now. No need to explain here though any better than helloworld922 and copeg.

6. ## Re: calculate sum and product

One other thing about your coding style, indenting a statement does NOT make it be inside of the if statement's block. If you look at the printout from your code you will see a repeated printout. Did you expect that?
You should ALWAYS use {}s to delimit the statements following if, else, while etc.
90% of the time that you don't, it causes an error when you try to add another statement.

7. ## Re: calculate sum and product

A tip:
Whenever initializing a variable to keep track of a product, initialize it to the first entry or factor.

```//do not do this
int product = 0;
product *= intArray[0];
product *= intArray[1];
product *= intArray[2];
...

//do this
int product = intArray[0];
//or
int product = 1;```

Also:
```if (count == 5)
System.out.println("Sum = " + sum);
System.out.println("Product = " + product);```
Java allows syntax for using the if statement implicitly with no braces, but only one statement following the if clause is counted in the implied "then" clause. If you use braces, you are being explicit and explicit is better.