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.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cmath>
#include <stdlib.h>
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<<endl;

	while (i=1,i<=n,i++)
{
        while (a<=n)
     {        
        a=a+d;
        cout<<a<<" , "; 
     } 

}






    system("pause");
    return 0;

}
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:

1
2
3
4
5
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.