sum of numbers in vector

let's say i want to sum five numbers in a vector.

1 2 3 4 5

but i want to leave one number off.

like this:

2 + 3 + 4 + 5
1 + 3 + 4 + 5
1 + 2 + 4 + 5
1 + 2 + 3 + 5
1 + 2 + 3 + 4

how can i do that?

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

int main()
{
	int sum = 0;
	vector<int> numbers(5);
	for (int i = 0; i < 5; i++)
	{
		cin >> numbers[i];
	}

	for (int i = 0; i < 5; i++)
	{
		
	}
	system("PAUSE");
	return 0;
}
Last edited on
To total it up you can use

1
2
3
4
	for (int i = 0; i < 5; i++)
	{
		sum += numbers[i];
	}


If you want to leave one off use an if statement inside the for loop to test if your at the position vector you want to leave off.
\sum_{j=1}^n a_j \mid j \neq k
= \sum_{j=1}^{k-1} a_j + \sum_{j=k+1}^n a_j
= \sum_{j=1}^n a_j - a_k


http://www.uploadhouse.com/imgs/23327385/
@ne555 your link doesn't open
std::accumulate(numbers.begin(), numbers.end(), -numbers[position]);
Where position is the index of the element you want to exclude.
This actually computes the addition so it doesn't assume that the numbers are the first N positive integers.
Last edited on
Are you saying you want to delete one of the numbers, and then total them up? If you wanted to do that, you could just set one of the numbers in the array to zero, so it doesn't get calculated in the total.

For example:
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>
#include <string>
using namespace std;

int main()
{
    int array[5], total = 0, deleteNum;
    
    cout << "Enter five numbers: " << endl;
    
    for (int i = 0; i < 5; i++)
        cin >> array[i];
        
    cout << "Which array element would you like to delete? (0, 1, 2, 3, or 4) " << endl;
    cin >> deleteNum;
    
    cout << "Deleting array element " << deleteNum << ", which is " << array[deleteNum] << ". " << endl;
    //Doesn't really "delete" it, just sets the value to zero so it's not calculated in the sum
    array[deleteNum] = 0;
    
    for (int i = 0; i < 5; i++)
        total += array[i];
        
    cout << "The total of the numbers is: " << total << ". " << endl;
}


-VX
Topic archived. No new replies allowed.