programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Adding up odd numbers that the user enters

Greenhorn
Posts: 1
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
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
It can be done in a recursive method.

fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
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
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
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.