# calculate sum and product

• September 26th, 2011, 04:42 PM
swampfox
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:

Code Java:

```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
• September 26th, 2011, 05:23 PM
copeg
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.
• September 26th, 2011, 06:35 PM
swampfox
Re: calculate sum and product
Ugh, sorry, I still don't get it.
• September 27th, 2011, 12:11 AM
helloworld922
Re: calculate sum and product
Code Java:

`int product = 0;`
And later on:
Code Java:

`product *= count;`

0*1 = ?
0*2 = ?
0*3 = ?
...
• September 27th, 2011, 06:44 AM
Mr.777
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.
• September 27th, 2011, 09:35 AM
Norm
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.
• September 27th, 2011, 03:55 PM
kenster421
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.

Code :

```//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:
Quote:

Code :

```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.