
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Find the Number of Subarrays with Odd Sum using C++
- Find the Number With Even Sum of Digits using C++
- Binary Subarrays With Sum in C++
- Find the Number Of Subarrays Having Sum in a Given Range in C++
- Find the Number Of Subarrays Having Sum in a Given Range using C++
- Find the Number of subarrays having sum less than K using C++
- Count subarrays with Prime sum in C++
- Find sum of even factors of a number using C++.
- Even Number With Prime Sum
- Count subarrays with same even and odd elements in C++
- To find sum of even factors of a number in C++ Program?
- Number of Subarrays with Bounded Maximum in C++
- Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)
- Print all subarrays with 0 sum in C++
- C++ Program to find sum of even factors of a number?

Advertisements