I have a vector defined like this:

#include<iostream>
#include<vector>

using namespace std;
typedef vector<int> VECTORINT;

int main() {
	VECTORINT Vectorul;
	
	int x;
	int num;
	int y;
	cin>>num;  //the number of numbers that must be entered
	
	for(int i = 0; i<num; i++){cin>>x;
	Vectorul.push_back(x);
	  for(int i=0; i<Vectorul.size(); i++)
	cout<<Vectorul[i]<<endl;

}

	
	system("pause");
	return 0;
}

After I get the input numbers I want to add them to one each other ex:
I get the numbers 1,2,3 and after I want to add the 1+2+3.
Anyone has any idea how to do this?

Recommended Answers

All 10 Replies

You could just create an int called sum with an initial value of 0 and then make a for() loop just add all the elements to sum one by one until the end of the vector.

I tried like this but is not working

for(int i = 0; i>Vectorul.begin() & i<Vectorul.end(); i++){
		
	y=i++;
	cout<<y<<endl;
	}

You can use the accumulate function like jonsca said or you can just use a for() loop and add them all up. Since you didn't know how to add a vector up I would recommend using this method so you can figure out what is going on then maybe use the accumulate function later.

#include<iostream>
#include<vector>

using namespace std;
typedef vector<int> VECTORINT;

int main()
{
	VECTORINT Vectorul;

	int x;
	int num;
	int y = 0; //sum?
	cin >> num;  //the number of numbers that must be entered

	for( int i = 0; i < num; i++ )
	{
		cin >> x;
		y += x; //either add them here
		Vectorul.push_back(x);
		for( int j = 0; j < Vectorul.size(); j++ ) //do not nest for() loops with the same variable
			cout << Vectorul[j] << endl; //seems kinda pointless and just clutters the input/output
	}

	for( int i = 0; i < Vectorul.size(); i++ )
		y += Vectorul[i]; //or add them here BUT do not include both of these sections

	system("pause");
	return 0;
}

Is not working .
Is not adding them.
Just shows me the numbers I entered.

Post what you put in. I tested this before I posted.

lines 21 and 22 are from your original code. Delete them if you do not want to see your inputs every time.

I added exactly what you wrote and I commented once line 19 and after that I commented line 25 and 26 and uncommented line 19, and after that I uncommented both of them and still doesn't want to work.

Did you throw in a cout << y << endl; at the end?

Is working, thank you.
I also tried with accumulate like this
total = accumulate(Vectorul.begin(), Vectorul.end(), 0);
and it works.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.