#include <iostream>
#include <cmath>
using namespace std;
class EOF_Exception : public exception {};
// Input an integer in a loop until given a valid number
int inputInteger(const char* message){
int n;
while(1){
cout << message;
cin >> n;
// Throw exception if end-of-file (EOF) is given on input
if(cin.eof()) throw EOF_Exception();
// Break this loop only the input is valid, otherwise print and error and redo.
if(!cin.fail()) break;
cout << "ERROR: Invalid integer input" << endl;
}
return n;
}
// A struct to hold the bounds and length() for the number of ..numbers.. in the range.
typedef struct {
int lower;
int upper;
int length(){ return upper - lower + 1; }
} Range;
// Inputs the bounds in a loop until valid bounds are given (lower <= upper)
Range inputRange(){
Range range;
while(1){
range.lower = inputInteger("Enter lower limit: ");
range.upper = inputInteger("Enter upper limit: ");
// Break this loop only the range is valid, otherwise print and error and redo.
if(range.lower <= range.upper) break;
cout << "ERROR:" "lower bound (" << range.lower << ") is greater than " \
"upper bound (" << range.upper << ")" << endl;
}
return range;
}
// Iterates the given range and performs the summation + count of even numbers
// NOTE: Calculating the even/odd numbers can be done directly from the bounds without a loop
// which is probably better. I didn't bother, but you can lol =)
// NOTE: Printing is also done here for simplicity, but it is preferable to avoid mixing
// "user interface" operations (like printing to console) with "business logic" (our algorithm).
void iterate_range(Range range){
int sum = 0, num_odds = 0;
// NOTE: I thought of making a custom iterator to make this more elegant, but for
// simplicity I've left it the way it is
for(int n = range.lower; n <= range.upper; ++n){
sum += n;
if(sum % 2) ++num_odds;
// Printing the sum, spaces are added only in between (it annoys me otherwise)
if(n != range.lower) cout << " ";
cout << sum;
}
// Print a new line character at the end of the lsit of sums printed in the loop.
cout << endl;
cout << "Even nubmers: " << range.length() - num_odds << endl;
cout << "Odd numbers: " << num_odds << endl;
}
// The entry point to the program.
int main(int argc, char **argv){
try{
Range range = inputRange();
iterate_range(range);
}
catch(EOF_Exception& e){
return 1;
}
return 0;
}