--Originally published at Programming Path
The activity is to run a program where it gives you the sum of a range of numbers, which that range is asked to the user. We needed to be careful if the user inserts the numbers in the wrong order. If that happens then we should put something like “your wrong, please enter it again.
Here is the code:
Again the code:
#include <iostream>
using namespace std;
int main () {
int l, h, i, r = 0;
cout << “I will sum the numbers in the range you give.” << endl;
cout << endl << “Please enter the lowest number: “;
cin >> l;
cout << “Please enter the highest number: “;
cin >> h;
if (h < l) {
cout << “That number is lower than the first one, please don’t joke around.” << endl;
cout << “Enter the highest number again, please: “;
cin >> h;
}
if (l == 0) {
for (i = 0 ; i <= h; i++) {
r = r + i;
}
}
else {
for (i = l; i <= h; i++) {
r = r + i;
}
}
cout << “The sum from ” << l << ” to ” << h << ” is: ” << r << endl;
return 0;
}
This are the result, with two options:
Wrong order:
I will sum the numbers in the range you give.
Please enter the lowest number: 3
Please enter the highest number: 2
That number is lower than the first one, please don’t joke around.
Enter the highest number again, please: 7
The sum from 3 to 7 is: 25
Right order:
I will sum the numbers in the range you give.
Please enter the lowest number: 3
Please enter the highest number: 7
Continue reading "(WSQ04) Please, don’t joke around" →