Problem Statement - Sum of even and odd values in an array
Write the definition of a function SumEO(int VALUES[], int N) in C++, which should display the sum of even values and sum of odd values of the array separately.
Example: if the array VALUES contains
25 20 22 21 53
Then the functions should display the output as:
Sum of even values = 42 (i.e 20+22)
Sum of odd values = 99 (i.e 25+21+53)
Solution
TC++ #5270
void SumEO(int VALUES[], int N)
{
int SE = 0, SO = 0;
for (int I=0;I<N;I++)
{
if(VALUES[I] %2 == 0)
SE += VALUES[I];
else
SO += VALUES[I];
}
cout<< "Sum of even values = " << SE<<endl;
cout<< "Sum of odd values = " << SO<<endl;
}
Notes
int SE = 0, SO = 0; //Sum of Even SE and Sum of Odd SO has to be initialized with 0 so that final additions can be done in these variables. for (int I=0;I<N;I++) { //This loop runs till array length passed as N if(VALUES[I] %2 == 0) SE += VALUES[I]; // This check is for even numbers, by testing remainder after dividing by 2, which is successively added to SE. else SO += VALUES[I]; //Otherwise assuming odd numbers will be successively added to SE
} cout<< “Sum of even values = ” << SE<<endl; cout<< “Sum of odd values = ” << SO<<endl;
Relevant values are printed.
}