Sum a sequence of integers

Oct 7, 2009 at 2:37pm
I need help with this bit of code. First integer is the number of values remaining to be entered and only one value can be inputed per statement.

So if I enter a 5, I should be allowed to enter 5 more ints and then all those ints need to be added together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
using namespace std;



int main()
{

    int number;
    int sum = 0;
    
    cout << "Enter the first number:";
    cin >> number;

    sum = 0;
    for (int counter = 1; counter <= number; counter++)
    {    
        cout << sum + number << endl;
    }
        cout << sum << endl;
    return 0;
}

The output is just

Enter the first number: 5
5
5
5
5
5

Oct 7, 2009 at 2:41pm
Read input in the loop to get the new values and add them to 'sum' ( ie: sum += input_you_get; // make 'sum' increasing )
Notice that you will need to get input in a new variable ( not 'number' ) or your loop will go crazy
Oct 7, 2009 at 2:45pm
Like this?

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
#include <iostream>
using namespace std;



int main()
{

    int number;
    int sum = 0;
    int input = 0;
    

    cout << "Enter the first number:";
    cin >> number;

    sum += input;

    for (int counter = 1; counter <= number; counter++)
    {    
        cout << sum + number << endl;
    }
 
    return 0;
}


Oct 7, 2009 at 3:04pm
move line 17 inside the loop and read input from the user
Oct 7, 2009 at 3:04pm
No, you need to get input inside the for loop (otherwise you will keep using "number", which isn't supposed to change).
Oct 7, 2009 at 5:24pm
Hmm. Like this? I moved it inside the loop, and read input from the user which is the variable number right?

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
#include <iostream>
using namespace std;



int main()
{

    int number;
    int sum = 0;
    int input = 0;
    

    cout << "Enter the first number:";
    cin >> number;

    for (int counter = 1; counter <= number; counter++)
    {    
       
      sum += input;
      cin >> number;
      cout << sum + number << endl;

    }
 
    return 0;
}
Oct 9, 2009 at 2:20pm
You are not reading into 'input'...
Oct 10, 2009 at 8:55am
the value of 'input' is always 0,not what you enter.
Oct 10, 2009 at 3:53pm
#include<iostream>
using namespace std;


void main()
{
int iNumberInputs;
int sum=0;
cout << "NuberInputs" << endl;
cin >> iNumberInputs;
int* iInputs = new int[iNumberInputs];
for (int x = 0; x<iNumberInputs; x++){
cout << "Inputs: "<< endl;
cin >> iInputs[x];
}
for (int y = 0; y<iNumberInputs; y++){
sum = sum+iInputs[y];
}
cout << sum << endl;
}
Topic archived. No new replies allowed.