In: Computer Science
SOURCE CODE:
#include <iostream>
using namespace std;
int main() {
int a,b; //declaring two integer variables a and
b..
cout<<"Enter the value of a= ";
cin>>a; //taking input from user, the value of
a..
cout<<endl; //new line..
cout<<"Enter the value of b= ";
cin>>b; //taking input from user, the value of
b..
cout<<endl; //new line..
int evenSum=0, oddSum=0;
for(int i=a; i<=b; i++) //for loop is iterated from
i=a to i=b with incrementation of 1 each time to get all numbers
between a and b..
{
if(i%2==0) //if its remainder with 2 is 0.. it means
it is even..hence taking all even numbers between a and b
here..
{
evenSum=evenSum+i; //adding all even numbers and
storing it back in evenSum..
}
else{ //if a number is not even it would be odd..hence
taking all odd numbers between a and b here..
oddSum=oddSum+i; ////adding all odd numbers and
storing it back in oddSum..
}
}
cout<<"Sum of the even numbers between
"<<a<<" and "<<b<<" is
"<<evenSum<<endl; //printing the sum of even
numbers..
cout<<"Sum of the odd numbers between
"<<a<<" and "<<b<<" is
"<<oddSum<<endl; //printing the sum of odd
numbers..
return 0;
}
OUTPUT:
NOTE: Since, Output of the test case was not shown and nothing was mentioned about whether we have to include a and b.
So, I have given the code which includes the value of a and b while calculating sum of odd and even numbers between them.
If you want the code which excludes the value of a and b while calculating sum of odd and even numbers between them. Please feel free to comment I will do the respective changes according to you.
Please verify in the comment section if this is what you want.
I have mentioned comments wherever necessary in the code. Please copy the entire code and save it with ".cpp" extension, then compile and run.
Hope it Helps..!!
Thanks..