C++ Program to print the sum of n odd and even numbers using do while
Program
#include <iostream>
using namespace std;
int main()
{
int i, n;
int e_sum = 0;
int o_sum = 0;
cout << "Enter the value of n \n";
cin >> n;
i = 1;
do
{
if (i % 2 != 0)
{
o_sum = o_sum + i;
}
else
{
e_sum = e_sum + i;
}
i++;
} while (i <= n);
cout << "Sum of all odd numbers from 1 to " << n << " is:" << o_sum;
cout << endl;
cout << "Sum of all even numbers from 1 to " << n << " is:" << e_sum;
return 0;
}
Output
$ g++ sum-of-n-odd-and-even-numbers-using-do-while.cpp
$ ./a.out
Enter the value of n
10
Sum of all odd numbers from 1 to 10 is:25
Sum of all even numbers from 1 to 10 is:30