• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding up odd numbers that the user enters  RSS feed

 
John Bradshaw
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using a For loop how would you calculate the sum of all the odd numbers up to a certain number? e.g. User inputs 5 and the answer is 9 as 1+3+5 =9.
Any help is appreciated on how to do this calculation.



 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How would you do it?

I don't mean how would you write the java code. I mean if you had pencil, paper, and a big eraser, how would you figure this out?

once you know that, try explaining to a child how THEY should do it, step by step.  Where to start? where to end?  what EXACT steps would you (or they) take?
 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can be done in a recursive method.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naziru Gelajo wrote:It can be done in a recursive method.

How can it be done recursively when the spec says to use a for loop?
 
Paul Clapham
Sheriff
Posts: 22838
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
fred rosenberger wrote:
Naziru Gelajo wrote:It can be done in a recursive method.

How can it be done recursively when the spec says to use a for loop?


It doesn't need any loops at all, there's a simple mathematical formula which gives you the required output directly. But that's also irrelevant; John's code is supposed to use a for-loop so that's what it should do.
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naziru Gelajo wrote:It can be done in a recursive method.
We are trying to persuade the OP to work out what to do rather than how to do it.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!