How to sum up a vector/array

Feb 2, 2012 at 1:12pm
Hi all.

Looking for help on how to sum up the components of a vector/array. The basic outline is that I input a vector/array a of length N,and want the sum of the square of the components. I have defined a vector/array b which is just hte components of a squared, so all I need to do is sum it up. Only problem is, I don't know how! Help please.

Here is my program thus far:

#include <iostream>
using namespace std;

int main(void)

{
int N; int a[11]; int n; int b[11];

//Entering and printing N
cout<<"Enter the dimension of the vector, between 1 and 10 "<<endl;
cin>>N;
cout<<"N="<<N<<endl;

//Entering the vector components

cout<<"Enter the vector components for the vector of dimension size N, as specified above"<<endl;

for(n=1; n<N+1; n=n+1)
{
cout<<"a["<<n<<"]=";
cin>>a[n];
}

//Summing the square of the vector components
for (n=1; n<N+1; n=n+1)
{b[n]=(a[n])*(a[n]);
cout<<b[n]<<endl;
}

return(0);
}

Feb 2, 2012 at 1:38pm
Declare a variable "total", set it to 0, loop through the array/vector and add the current element to "total". You already have the looping code (twice, even!), you already have variable declarations (four, even!) and you already have an example of array-accessing and how to perform operations on them. This should be a piece of cake!
Feb 2, 2012 at 1:50pm
I figured it was a relativly simple thing that I would be stupidly forget!

However, I don't really understand what you mean by "loop through the array/vector and add the current element to "total". ".
Feb 2, 2012 at 2:07pm
Exactly what I said. Access each element (n = 1 -> N) and add it to total (total += b[n]).
Feb 2, 2012 at 2:28pm
Sorry, but what exactly do you mean by accessing elements and looping through arrays?

Sorry, I don't mean to sound thick :)
Feb 2, 2012 at 2:30pm
I'm very confused you don't understand, since you already used it...
1
2
3
4
5
6
//Summing the square of the vector components
for (n=1; n<N+1; n=n+1) // 'loops' from n = 1->N
{
    b[n]=(a[n])*(a[n]);  // 'accesses' the elements, and assigns one element a value
    cout<<b[n]<<endl;
}

Just do the same, but instead, turn the 4th line into 'total += b[n];'.
Feb 2, 2012 at 2:38pm
1
2
3
4
5
int sum = 0;
for(n=0;n<N;n++)
{
  sum += b[n];
}
Feb 2, 2012 at 2:45pm
Gaminic, that works, however it lists the answer for every n. i.e. N =4, a[1]=1, a[2]=2, a[3]=3, a[4]=4, it returns 1,5,14,30.

Is there a way to only have it list the last number?
Feb 2, 2012 at 3:02pm
Move the 'cout' outside the for loop.
Feb 3, 2012 at 9:36am
Brilliant, that works if I get it to print out b[N]

Thanks for your help!
Topic archived. No new replies allowed.