change fuction

Hello,my program sum min and max number in vector.
How to change the function in this code to give the sum of even numbers
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
28
29
30
31
32
33
34
35
36
  
#include<iostream>
#include<vector>
using namespace std;

void printSumMaxMin(const vector<int>& numsVec) 
{
	int sz = numsVec.size();
	int min = numsVec[0];
	int max = numsVec[0];
	for (int i = 1; i < sz; i++)
	{
		if (min > numsVec[i])
		{
			min = numsVec[i];
		}
		else if (max < numsVec[i])
		{
			max = numsVec[i];
		}
	}
	cout << max + min << endl;
}

int main() 
{
	int n, x;
	cin >> n;
	vector<int> numsVec;
	for (size_t i = 0; i < n; i++)
	{
		cin >> x;
		numsVec.push_back(x);
	}
	printSumMaxMin(numsVec);
}
Last edited on
To test for odd/even, divide the number by two using the modulus operator. If it divides evenly into itself, then it's an even number. If not, then the number's odd. I hope this helps you.
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
28
29
#include<iostream>
#include<vector>
using namespace std;

void printSumMaxMin(const vector<int>& numsVec) 
{
    int total {0};
    for(auto vecNum:numsVec){
        if(vecNum % 2 == 0)  // (vecNum % 2 != 0) to test for odd
            total += vecNum;
    }
    cout << total;
}

int main() 
{
    int n, x;
    cin >> n;
    vector<int> numsVec;
    for (size_t i = 0; i < n; i++)
    {
        cin >> x;
        numsVec.push_back(x);
    }

    printSumMaxMin(numsVec);

    return 0;
}
Last edited on
Why change? Add a separate function. (You can delete unused functions later.)

Do you know how to calculate the sum of values of an array?
Topic archived. No new replies allowed.