C++ Program to print the sum of n odd and even numbers using while
Program
#include <iostream>
using namespace std;
int main()
{
int i, n;
int o_sum = 0;
int e_sum = 0;
cout << "Enter the value of n \n";
cin >> n;
i = 1;
while (i <= n)
{
if (i % 2 != 0)
{
o_sum = o_sum + i;
}
else
{
e_sum = e_sum + i;
}
i++;
}
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-while.cpp
$ ./a.out
Enter the value of n
5
Sum of all odd numbers from 1 to 5 is:9
Sum of all even numbers from 1 to 5 is:6