C++ Program to print the sum of n odd and even numbers within range using while
Program
#include <iostream>
using namespace std;
int main()
{
int start_range, end_range;
int o_sum = 0;
int e_sum = 0;
cout << "Enter the starting range: ";
cin >> start_range;
cout << "Enter the ending range: ";
cin >> end_range;
int i = start_range;
while (i <= end_range)
{
if (i % 2 != 0)
{
o_sum = o_sum + i;
}
else
{
e_sum = e_sum + i;
}
i++;
}
cout << "Sum of all odd numbers in given range is :" << o_sum;
cout << endl;
cout << "Sum of all even numbers in given range is :" << e_sum;
return 0;
}
Output
$ g++ sum-of-n-odd-and-even-numbers-within-range-using-while.cpp
$ ./a.out
Enter the starting range: 30
Enter the ending range: 50
Sum of all odd numbers in given range is :400
Sum of all even numbers in given range is :440