c++ vector sum of elements helping

Dec 5, 2017 at 2:18pm
this is my code
#include <iostream>
#include<conio.h>
#include <vector>
using namespace std;
int main() {
int n,sum=0;
cout<<"Input n:";
cin>>n;
vector<int> x(n);
cout<<"input of elements";
for(int i=0;i<x.size();i++) {
cout<<x[i]<<endl;
sum+=x[i];
}
cout<<"sum"<<sum<<endl;
getch ();
return 0;
}
this program is running but ı want to sum of elements
Dec 5, 2017 at 3:28pm
You've allocated memory to the std::vector<int> x but haven't actually put any values in it's cells. This needs to be done (hint: push_back()) and then the elements of the vector can be summed through a loop as you've shown for by using std::accumulate (#include <algorithm>)
Dec 5, 2017 at 3:30pm
it does that.
you read in the size of a vector
then you create the vector of that size
then you loop over the vector and write out the uninitialized values and sum them
then you write out the sum

what you don't do is read in the vector elements or assign them something simple.

try this..
vector<int> x(n, 2);

sum written should be 2*n now.
you should be able to adapt from there to do whatever it is you want (maybe cin each entry THEN add it up??)
Dec 5, 2017 at 7:36pm
#include <iostream>
#include<conio.h>
#include <vector>
using namespace std;
int main() {
int n,sum=0;
cin>>n;

vector<int> x(n);

for(int i=0;i<x.size();i++) {
cout<<x[i]<<endl;
x.push_back(i);
sum=sum+x[i];
}


getch ();
return 0;
}
I tried this code it is running but someting is mistake can you help me?what is the wrong in my code please?
Dec 5, 2017 at 7:56pm
assign values to x.

either
cin >> x[i];
or
for(..)
x[i] = 2; //whatever value...

or something like that.

or, to make it very clear: what is the current value of x[0] in your code? Try to answer that.
Dec 5, 2017 at 8:06pm
Line 9 reserves n elements. It does not initialize them.

Lines 12-13 are in the wrong order. You want to push the value onto the vector before trying to cout the value.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.

Topic archived. No new replies allowed.