id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

orion.a.smith@gmail.com apcsa-loops > apcsaLoopsAddEveryOddInclusive
prev  |  next  |  chance

Given two ints a and b, add every ODD number between a and b, inclusive of a and b if both are odd, or possibly inclusive of neither if both are even. So if a is 4 and b is 7, the result should be 12, the result of 5+7. Precondition: a < b.


HINTS

Remember that the remainder operator % can be used to find the remainder during division.  When you divide an odd positive number by 2, the remainder is 1.  When you divide an odd negative number by 2, the remainder is -1.  Thus, you could use Math.abs(num % 2) to find the absolute value of the remainder and deal with both positive and negative inputs.

The above advice works if you use some kind of if statement inside your loop to test each value and see if it should be added to the sum (a pretty common pattern with loops).  Another approach is the realization that, if you can find the correct starting value, every odd number is 2 less than the next odd number.

apcsaLoopsAddEveryOddInclusive(4, 7) → 12
apcsaLoopsAddEveryOddInclusive(5, 8) → 12
apcsaLoopsAddEveryOddInclusive(-10, -4) → -21

...Save, Compile, Run (ctrl-enter)

public int apcsaLoopsAddEveryOddInclusive(int a, int b) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 150

Copyright Nick Parlante 2017 - privacy