Add minimum number to an array so that the sum becomes even in C++?

C++Server Side ProgrammingProgramming

Suppose there is an array with some numbers. We have to tell minimum how many numbers will be added with it to make the sum of the elements even. The number must be greater than 0. So if the sum of the elements is odd, we will add 1, but if the sum is already even, then we will add 2 with it to make it even.

Algorithm

addMinNumber(arr)

begin
   s := 0
   for each element e from arr, do
      s := e + s
   done
   if s is even, then return 2, otherwise 1
end

Example

 Live Demo

#include<iostream>
using namespace std;
int addMinNumber(int arr[], int n) {
   int sum = 0;
   for(int i = 0; i<n; i++) {
      sum += arr[i];
   }
   return (sum % 2)? 1 : 2;
}
main() {
   int arr[] = {5, 8, 4, 7, 5};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout << "Minimum " << addMinNumber(arr, n) << " should be added";
}

Output

Minimum 1 should be added
raja
Published on 24-Jul-2019 16:16:52
Advertisements