Count Pairs from two arrays with even sum in C++

C++Server Side ProgrammingProgramming

We are given two arrays of integer type elements let’s say, arr_1[] and arr_2[] and the task is to pick one element from arr_1[] and another element from arr_[] to form a pair then calculate the sum of elements in the pair and check whether the resultant sum is even or not.

Input 

int arr_1[] = {2, 3, 7, 1, 4}
int arr_2[] = { 2, 4, 1, 3}

Output 

Count Pairs from two arrays with even sum are: 10

Explanation 

We will form the pairs using both the arrays and the pairs so formed are-:
(2, 2) = 4(valid), (2, 4) = 6(valid), (2, 1) = 3(invalid), (2, 3) = 5(invalid), (3, 2) = 5(invalid), (3, 4) = 7(invalid), (3, 1) = 4(valid), (3, 3) = 5(valid), (7, 2) = 9(invalid), (7, 4) = 11(invalid), (7, 1) = 8(valid), (7, 3) = 10(valid), (1, 2) = 3(invalid), (1, 4) = 5(invalid), (1, 1) = 2(valid), (1, 3) = 4(valid), (4, 2) = 6(valid), (4, 4) = 8(valid), (4, 1) = 5(invalid), (4, 3) = 7(invalid). There are 10 valid pairs formed using given two arrays that are even sums.

Input 

int arr_1[] = {3, 1, 2}
int arr_2[] = { 2, 4}

Output 

Count Pairs from two arrays with even sum are: 2

Explanation 

We will form the pairs using both the arrays and the pairs so formed are-:
(3, 2) = 5(invalid), (3, 4) = 7(invalid), (1, 2) = 3(invalid), (1, 4) = 5(invalid), (2, 2) = 4(valid), (2, 4) = 6(valid), . There are 2 valid pairs formed using given two arrays that are even sums.

Approach used in the below program is as follows

  • Input the two arrays of integer type elements and calculate the size of both the arrays and pass the data to the function for further processing.

  • Take a temporary variable as count to store the count of pairs with even sum

  • Start loop FOR from i to 0 till the size of array 1

  • Inside the loop, start another loop FOR from j to 0 till the size of array 2

  • Now store the sum of arr_1[i] and arr_2[j] in an integer variable let’s say sum

  • Check IF sum % 2 ==0 i.e. sum is even or not. IF yes then increment the count by 1.

  • Return the count

  • Print the result.

Example

 Live Demo

#include <iostream>
using namespace std;
int even_pair(int arr_1[], int size_arr1, int arr_2[], int size_arr2){
   int count = 0;
   int odd = 0;
   for(int i = 0 ;i <size_arr1 ; i++){
      for(int j = 0; j<size_arr2 ; j++){
         int even = arr_1[i] + arr_2[j];
         if(even % 2 == 0){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr_1[] = {2, 3, 7, 1, 4};
   int arr_2[] = { 2, 4, 1, 3};
   int size_arr1 = sizeof(arr_1) / sizeof(arr_1[0]);
   int size_arr2 = sizeof(arr_2) / sizeof(arr_2[0]);
   cout<<"Count Pairs from two arrays with even sum are: "<<even_pair(arr_1, size_arr1, arr_2, size_arr2);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count Pairs from two arrays with even sum are: 10
raja
Published on 31-Oct-2020 05:59:12
Advertisements