Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Andrea Menjivar
Greenhorn
Posts: 25
1
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

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

 
Fred Kleinschmidt
Bartender
Posts: 560
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Marshal
Posts: 55678
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh wow I can't believe I missed that. Thank you very much, my program worked with that suggestion
 
Campbell Ritchie
Marshal
Posts: 55678
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!