First, we declare one variable "sum" with value 0, and then we are going to use this variable to store sum of all even/odd numbers between 1 and N . Now we will ask user that whether to add even numbers or odd numbers and store this in a variable 'c'. Now after taking input (N) from the user, we will call function even_sum or odd_sum ,according to users choice entered before. Now , in that function we will declare a variable 'a' which will initially store first even/odd number, then we will continue a loop until 'a' is less than or equal to N.

using namespace std;
int odd_sum(int n)
{
int a=1; // first odd number
int sum=0;
while(a <= n) // loop for n numbers
{
sum=sum+a;
a=a+2; // for next odd number
}
return sum;
}
int even_sum(int n)
{
int a=2; // first even number
int sum=0;
while(a <= n) // loop for n numbers
{
sum=sum+a;
a=a+2; // for next odd number
}
return sum;
}
int main() {
int n,sum;
char c;
cout<<"Enter 'E' to find sum of even numbers\n";
cout<<"or Enter 'O' to find sum of odd numbers\n";
cin>>c;
cout<<"Enter n\n";
cin>>n;
if(c=='E' || c=='e')
{
sum=even_sum(n);
}
else
{
sum = odd_sum(n);
}
cout<<sum<<"\n";
return 0;
}

## Comments