Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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)
Answer:
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.
}
C. Sir| Created: 4-Dec-2018 | Updated: 5-Dec-2018|CBSE12A-2018