Write a function that takes a numeric or integer vector and

Write a function that takes a numeric or integer vector and adds up only the numbers whose integer parts are even.

Modify your answer to question above to include an option that allows you to choose whether to sum numbers whose integer parts are even or are odd.

Your function should have as a default that it gives the same output as the function in question 4. In other words, if the user doesn’t specify whether to sum evens or odds, the function should sum evens.

Hint: the function arguments should look like function(x, evens = TRUE)

Solution

PROGRAM CODE:

/*
* vectorSum.cpp
*
* Created on: 31-Jan-2017
* Author: kasturi
*/

#include <iostream>
#include <vector>
using namespace std;

/**
* Function to determine the sum of even or odd numbers in a vector
*/
int sum(vector<int> x, bool evens)
{
   int sum = 0;
   for(vector<int>::iterator it = x.begin(); it != x.end(); ++it)
   {
       int num = *it;
       if(evens)
       {
           if(num%2 == 0)
           sum += num;
       }
       else{
           if(num%2 != 0)
               sum += num;
       }
   }
   return sum;
}

int main()
{
   vector<int> numbers;
   for(int i=1; i<=20; i++)
       numbers.push_back(i);

   cout<<\"Sum of even numbers is : \"<<sum(numbers, true)<<endl;
   cout<<\"Sum of odd numbers is : \"<<sum(numbers, false)<<endl;
}

OUTPUT:

Sum of even numbers is : 110

Sum of odd numbers is : 100

Write a function that takes a numeric or integer vector and adds up only the numbers whose integer parts are even. Modify your answer to question above to inclu

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site