 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find number of subarrays with even sum in C++
In this problem, we are given an array arr[] consisting of N elements. Our task is to find the subarray with even sum.
Let’s take an example to understand the problem,
Input
arr[] = {2, 1, 3, 4, 2, 5}  Output
28
Explanation
The subarrays are −
{2}, {4}, {2}, {2, 4}, {2, 2}, {1, 3}, {1, 5}, {3, 5}, {4, 2}, {2, 1, 3}, {2, 1, 5}, {2, 3, 5}, {2, 4, 2}, {1, 3, 4}, {1, 3, 2}, {1, 4, 5}, {1, 2, 5}, {3, 4, 5}, {3, 2, 5}, {2, 1, 3, 4}, {2, 1, 3, 2}, {2, 3, 4, 5}, {2, 3, 2, 5}, {2, 4, 2, 5}, {1, 3, 4, 2}, {1, 4, 2, 5}, {3, 4, 2, 5}, {2, 1, 3, 4, 2}, {2, 1, 3, 4, 2, 5}  Solution Approach
A simple solution to the problem is using the direct method which is by calculating all subarray and their sums. And the increase count for the subarray with even sum. And at last return count.
Program to illustrate the working of our solution,
Example
#include<iostream> using namespace std; int countEvenSumSubArray(int arr[], int n){    int evenSumCount = 0, sum = 0;    for (int i=0; i<=n-1; i++){       sum = 0;       for (int j=i; j<=n-1; j++){          sum += arr[j];       if (sum % 2 == 0)          evenSumCount++;       }    }    return (evenSumCount); } int main(){    int arr[] = {2, 1, 4, 2};    int n = sizeof (arr) / sizeof (arr[0]);    cout<<"The count of Subarrays with even sum is "<<countEvenSumSubArray(arr, n);    return (0); }  Output
The number of solutions of the linear equation is 8
Advertisements
 