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
Re: calculate sum and product
For future reference, please wrap your code in the [highlight][/highlight] tags.
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.
Re: calculate sum and product
Ugh, sorry, I still don't get it.
Re: calculate sum and product
In your code:
And later on:
0*1 = ?
0*2 = ?
0*3 = ?
...
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.
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.
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.