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:

# while loops and all that fun stuff, need assignment help

Brandi Love
Ranch Hand
Posts: 133
I have to write a program that displays the sum of an arithmetic series that goes as follows
a+(a+d)+(a+2d)+(a+3d)....+(a+(n-1)d)
a is the first term
d is the "common difference"
n is the number of terms
The problem asks that you write a program for this statement in which a=1, d=3, and n=100. This is what I came up with for code:

I keep getting 0 as an answer for sum and I know that can't possibly be right. Any idea what I'm doing wrong? I know this problem is kind of hard to understand, I clarified it as best as I could.

Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Well, let's see. First, sum comes out as zero because the loop is never execute. The loop will execute while "n >= 100", which means "n is greater than or equal to 100." Because n starts out as 0, it's never greater than or equal to 100, so the loop never executes. I think you mean <=, not >=.
OK, now. At each step of the loop, you assign something to sum. But the previous value is being discarded. You want to write
sum = sum + (a + (a + (n - 1) * d));
so that the previous value is added in as well. You can write this using the "+=" shortcut if you want:
sum += (a + (a + (n - 1) * d));
Thirdly, about that expression: you want to add (a+(n-1)d) at each step, right? So it looks like you've got an extra "a" in there.
This should give the right answer, I think. But test it!
sum += (a + (n - 1) * d);

Aaron Roberts
Ranch Hand
Posts: 174
Your loop is never executing as you have -
while(n >= 100)
n starts off at 0, so your loop never executes. It should be flipped to n <=
Regards - Aaron R>
PS - Just after I posted, I noticed a much more complete one. Ernest has helped me in the past. (a custom plugin is a great thing!) So you can disregard my simpleton response;
[ October 27, 2003: Message edited by: Aaron Roberts ]

Brandi Love
Ranch Hand
Posts: 133
I can't believe I missed that, I was trying to figure out the problem for like half an hour. Thanks guys, the program runs wonderfully now.