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:

# For loop with parameter N that determines number of terms

Trish Huynh
Greenhorn
Posts: 4
Hi there! I am stuck on a study guide problem for class...

a. Write a code that is written inside a body of a method named average that takes two parameters: N that determines number of terms you should calculate the average of and lowBound that is the beginning term of the geometric sequence. if lowBound is 4 and N is 3, then the average of 4, 8, 16 is calculated and returned.

My code runs fine if I set the test as 16, but I can't figure out what I could do to N to have it determine the number of terms. This is what I have so far...

Any help would be appreciated.

Ak Jo
Greenhorn
Posts: 4
To calculate that value you call N , you should use this to calculate it =

double x=lowBound * Math.pow(2,(N-1));
for (double i=lowBound; i<=x;i*=2)

the x is the limiting value of your loop..e.g, if you give lowbound 4 & N is 4, your sequence is 4,8,16,32. x in this case will be 4 * (2,3) = 4*(2*2*2) =32. Works? Let me know.

Trish Huynh
Greenhorn
Posts: 4
Ak Jo wrote:To calculate that value you call N , you should use this to calculate it =

double x=lowBound * Math.pow(2,(N-1));
for (double i=lowBound; i<=x;i*=2)

the x is the limiting value of your loop..e.g, if you give lowbound 4 & N is 4, your sequence is 4,8,16,32. x in this case will be 4 * (2,3) = 4*(2*2*2) =32. Works? Let me know.

I never thought about it that way. Thanks so much!

Campbell Ritchie
Marshal
Posts: 56530
172
Welcome to the Ranch

I added code tags to your post. Always use them: doesn't it look a lot better You cannot use coloured text inside code tags, however.

Never use floating point numbers in a loop variable. There is a risk that you get 9.99999999999999something instead of 10 (or similar) and your loop will not work correctly. You ought to work that out using integer numbers. Remembering that the following integer divisions all equate to 1
3 / 2
2 / 2
5 / 4
1 / 1
and 1 / 2 is 0, consider using the loop with /= 2 instead. Start big and use i > 0 or i > 1 or similar as your continuation condition.

 Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters?