Friday 25 August 2017

Given an array, find the number of subarrays whose sum is even.

Input : arr[] = {1, 2, 2, 3, 4, 1}
Output : 9

There are possible subarrays with even sum. The subarrays are 
1) {1, 2, 2, 3}           Sum = 8
2) {1, 2, 2, 3, 4}       Sum = 12
3) {2}                       Sum = 2 (At index 1)
4) {2, 2}                   Sum = 4
5) {2, 2, 3, 4, 1}       Sum = 12
6) {2}                       Sum = 2 (At index 2)
7) {2, 3, 4, 1}           Sum = 10
8) {3, 4, 1}               Sum = 8
9) {4}                       Sum = 4 
 
                                     C-Solution 


#include<stdio.h>
void main()
{
    int num,i,j,count=0,sum=0;
    scanf("%d",&num);
    int a[num];
    for(i=0;i<num;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=0;i<num;i++)
    {
        sum=0;
        for(j=i;j<num;j++)
        {


            sum=sum+a[j];
            if(sum%2==0)
                count++;
        }
    }
    printf("%d",count);
}

No comments:

Post a Comment