# Adding odd numbers from 1 to 15

Printable View

• January 8th, 2013, 12:45 PM
kcassar
Adding odd numbers from 1 to 15
I have an exercise that wants me to write an application that calculates the product of the odd integers from 1 to 15, and displays the result.
Hereunder is the code that i have written, however I am not managing to count the odd numbers. Can someone help me please.
Code java:

public static void main(String[] args) {
int prod = 0;
int result = 0;
int div = 0;

for ( int i = 0; i != 16; i++ ) {

if (( i % 2 ) != 0)  {

prod = ( i * i );
result = (prod + prod);

System.out.println(prod);

}
}
}
}

• January 8th, 2013, 12:56 PM
Norm
Re: Adding odd numbers from 1 to 15
Quote:

however I am not managing to count the odd numbers.
Can you show what the program prints out and add some comments explaining what is wrong with what is printed and show what you want to be printed?

What is the variable: result used for?

Can you write an equation that shows how to get the product of the first 4 odd numbers?
• January 9th, 2013, 12:47 AM
imrllyhandsome
Re: Adding odd numbers from 1 to 15
did the exercise myself for practice
how do i wrap this in java code?

ok, so I read your code, and I think you should think it out on paper before even writing the code. Figure out how you wanna do it step by step then try to translate that into code, cause your code seems really off target.

so your code begins when i iterates to 1. Once i = 1, since 1%2 != 0, you do product = 1*1, after that you say result = 1 + 1 which is 2, then you print out product which is 1. So if you're not going to use result, what's the point of having it there in the first place?

>>>>>> Code removed
• January 9th, 2013, 06:24 AM
Norm
Re: Adding odd numbers from 1 to 15