Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++, Write a function named oddsEvens that takes in a vector of positive inte

ID: 3571848 • Letter: I

Question

In C++,

Write a function named oddsEvens that takes in a vector of positive integers and returns (via the parameters) how many of those integers are odd and how many are even. For example, if the vector had the following values {6, 5, 2, 10, 11, 4}, then the function would set the evens count to 4, and the odds count to 2. Obviously, if the vector is passed in empty, both counts will be set to 0. Give an example of the invocation of this function; you must show the declarations of any variables needed for this purpose, but you do not need to "populate" them - i.e. do not show where they are assigned values.

Explanation / Answer

#include <iostream>
#include <vector>
using namespace std;
void oddsEvens (vector<int> & v, int &oddCount, int &evenCount){
if(v.size() == 0){
oddCount = 0;
evenCount = 0;
}
else{
evenCount = 0;
oddCount = 0;
for(int i=0; i<v.size(); i++){
if(v[i] % 2 ==0){
evenCount++;
}
else{
oddCount++;
}
}
}
}
int main()
{
int oddCount, evenCount;
vector<int> v;
v.push_back(6);
v.push_back(5);
v.push_back(2);
v.push_back(10);
v.push_back(11);
v.push_back(4);
oddsEvens(v, oddCount, evenCount);
cout<<"Even count is "<<evenCount<<endl;
cout<<"Odd count is "<<oddCount<<endl;
  


return 0;
}

Output:

sh-4.2$ g++ -std=c++11 -o main *.cpp                                                                                                                                                                                                                   

sh-4.2$ main                                                                                                                                                                                                                                           

Even count is 4                                                                                                                                                                                                                                        

Odd count is 2