• Post Reply Bookmark Topic Watch Topic
  • New Topic

while loops and all that fun stuff, need assignment help  RSS feed

 
Brandi Love
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!