| 1. |
Given an array of positive integers, write code to return the differences between the sums of even and odd values in the given array. |
|
Answer» In this scenario, we would have to write a function "evenOddDiff" which takes two inputs as parameters: the number of positive integers in the array and the array of positive integers. For example, if the initial INPUT is 3 numbers and the numbers are 5, 2 and 4, the difference between the sums of even and odd numbers is = (4+2) – (5) = 6 – 1 = 5 The C++ code for the above-mentioned problem is given below: #include<bits/stdc++.h>using namespace std;int evenOddDiff(int n, vector<int> &a){ int oddSum = 0,evenSum = 0; for(int i: a) { if(i & 1) oddSum += i; else evenSum += i; } return evenSum - oddSum;}int main(){ int n; cin>>n; vector<int> a(n); for(int j = 0; j < n; j ++)cin >> a[j]; cout << evenOddDiff(n, a) << ENDL; return 0;}In the above-given code, we simply ITERATE over the elements of the list (given to US in the form of a C++ vector) and check whether each element of the list is an odd number or an even number using the condition "if(i && 1)". We also maintain two variables "oddSum" and "evenSum" which store the sum of odd numbers in the list and the sum of the even numbers in the list respectively. In the end, we simply return the difference between the values of the variables evenSum and oddSum as expected in the question. |
|