Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Find the product of even numbers up to 25 using a while loop

Greenhorn
Posts: 25
1
Hi, I'm new to Java and had an assignment for my class where I needed to write a program that calculated and displayed the sum of odd numbers 1-50 and the product of even numbers 1-25 using just a basic while loop. I got the portion with the odd numbers down but am confused with the part where you need to calculate the even numbers. The code below is what I turned in but my teacher commented that I should not initialize my even variable to 4 and should have instead been 0 or 2. I have tried these numbers but I will either get a different product entirely or end up with zero as the displayed product. How do I rewrite that portion of the code? I'm having a hard time understanding how to make it work without doing it the way I did.

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Bartender
Posts: 585
9
What happens if you initialize product=one, and even=two?

Since you increment odd and even using the += operator, why don't you use the += operator to update sum, and the *= operator to  update product?

Marshal
Posts: 57453
175
Welcome to the Ranch

To find out whether your teacher is right (or not) to say start from 2: write down all the even numbers from 2 to 25 and against them write down what you are multiplying. I think you will find he is right.

Andrea Menjivar
Greenhorn
Posts: 25
1
Oh wow I can't believe I missed that. Thank you very much, my program worked with that suggestion

Campbell Ritchie
Marshal
Posts: 57453
175
Now try the same with even numbers from 2…50. With any luck you will get arithmetic overflow, and you will have to use this to contain the size of result you get.

Well done sorting it out

 It runs on an internal combustion engine. This ad does not: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS