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


Given an array, add the minimum number (which should be greater than 0) to the array so that the sum of array becomes even.

Input - 1 2 3 4,

Output - 2

Explanation - Sum of array is 10, so we 

add minimum number 2 to make the sum even.

Method 1: calculate the sum of all elements of the array, then check if the sum is even then add minimum number is 2, else add minimum number is 1.

Input - 1 2 3 4,

Output - 2

Explanation - Sum of array is 10, so we add minimum number 2 to make the sum even.

Example

#include<iostream>
using namespace std;
int main() {
   int arr[] = { 1, 2, 3, 4};
   int n=4;
   int sum=0;
   for (int i = 0; i <n; i++) {
      sum+=arr[i];
   }
   if (sum % 2==0) {
      cout <<"2";
   } else {
      cout <<"1";
   }
   return 0;
}

Method 2 - calculate count of odd number of elements in the array. If count of odd numbers present is even we return 2, else we return 1.

Input - 1 2 3 4 5

Output - 1

Explanation - no. of in the array is 3
add minimum number 1 to make the sum even.

Example

#include<iostream>
using namespace std;
int main() {
   int arr[] = { 1, 2, 3, 4,5};
   int n=5;
   int odd = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 2!=0) {
         odd += 1;
      }
   }
   if (odd % 2==0) {
      cout <<"2";
   } else {
      cout <<"1";
   }
   return 0;
}

Method 3 - Take a flag variable (initialized as 0). Whenever we find the odd element in the array we perform the NOT(!) operation on the boolean variable. This logical operator inverts the value of the flag variable (meaning if it is 0, it converts the variable to 1 and vice-versa).

Input - 1 2 3 4 5

Output - 1

Explanation - variable initialized as 0.
Traversing the array
1 is odd, variable changed 1.
2 is even
3 is odd, variable changed 0.
4 is even
5 is odd, variable changed 1

If variable value is 1 it means odd number of odd elements are present, minimum number to make sum of elements even is by adding 1.

Else minimum number is 2.

Example

#include<iostream>
using namespace std;
int main() {
   int arr[] = { 1, 2, 3, 4,5};
   int n=5;
   bool odd = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 2!=0) {
         odd = !odd;
      }
   }
   if (odd) {
      cout <<"1";
   } else {
      cout <<"2";
   }
   return 0;
}
raja
Published on 09-Aug-2019 13:22:25
Advertisements