C++ Program to print the sum of n odd and even numbers within range using for
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;
for (int i = start_range; i <= end_range; i++)
if (i % 2 != 0)
{
o_sum = o_sum + i;
}
else
{
e_sum = e_sum + 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-for.cpp
$ ./a.out
Enter the starting range: 70
Enter the ending range: 100
Sum of all odd numbers in given range is :1275
Sum of all even numbers in given range is :1360