### need help with arithmetic sequence code

This code is suppose to display arithmetic sequence after it has to add all the numbers together without a formula.

for example: the starting number is 5, common difference is 3, the term is 9

the sequence would display as: 5, 8, 11, 14, 17, 20, 23, 26, 29
the sum is: 153

with my code I've managed to get 8,11

to get the sum, I am restricted to using a "for" loop. For sequence, I am using a while.
I am trouble developing the while loop to display the sequence and getting the sum for the for loop.

 ``12345678910111213141516171819202122232425262728293031323334353637383940`` ``````#include #include #include using namespace std; int main() { double a, d, n,i,sum,j; char flag = 'y'; //y for yes to reset cout <<"Enter starting value "; cin >> a; cout <<"Enter difference "; cin >> d; cout <<"Enter a term "; cin >> n; cout<
Hi there,

Let's write a for loop for this:

`for (int i=a; i<((n-1)*d+a); i+=d)`

I'll break it down for you:

`int i=a` We use a counter variable called i, set it to equal the starting value
`i<=((n-1)*d+a)` Our for loop should stop when the counter i is equal to (or larger than) starting value + difference * (term-1). For your example: i <= (9-1)*3+5=29
`i+=d` After each iteration, increment our counter i with difference.

To keep the sum, you just need to increment it with the current i counter in the for loop:

 ``12345`` ``````for (int i=a; i<((n-1)*d+a); i+=d) { sum += i; std::cout << i << ", " }``````

Hope that makes sense to you.
Please do let us know if you have any further questions.

All the best,
NwN
Thank you,so much. I think i am understanding it a little bit.
Most welcome, please do let us know if you have any further questions.

All the best,
NwN
Topic archived. No new replies allowed.