In: Computer Science
Write a program that will sum the integers between a given range (limit your range from 0 to 50). For example, if the user want to add the integers between (and including) 1 and 10, then the program should add:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
Algorithm:
Test data (Use this data to test to ensure your program does the math correctly.):
#include <iostream>
using namespace std;
int main() {
//Declaring variable start,stop and sum
int start, stop, sum = 0;
//Prompt input from users Start value
cout << "Start value: ";
//accepting Start value
cin >> start;
//Prompt input from user Stop value
cout << "Stop value: ";
//accepting stop value
cin >> stop;
//looping from start to stop value
for (int i = start; i <= stop; i++)
//adding each value with sum
sum += i;
//printing out the sum
cout << "Sum: " << sum <<
endl;
return 0;
}
add error checking to it.
Check the user’s start value to see if it falls within the accepted range. If it doesn’t, the program should tell the user that their input wasn’t in the accepted range and ask the user to reenter a value within the range.
Do the same thing with the stop value.
Once both values are determined to be within the accepted range, then continue with the program.
#include <iostream>
using namespace std;
int main()
{
//Declaring variable start,stop and sum
int start, stop, sum = 0;
//Prompt input from users Start value
cout << "Start value: ";
//accepting Start value
cin >> start;
// Check the user’s start value to see if it falls within the accepted range.
while (start < 0 || start > 50)
{
// If it doesn’t, the program should tell the user that
// their input wasn’t in the accepted range and
cout << "Please enter a value from 0 to 50\n";
// ask the user to reenter a value within the range.
cout << "Start value: ";
cin >> start;
}
//Prompt input from user Stop value
cout << "Stop value: ";
//accepting stop value
cin >> stop;
// Check the user’s stop value to see if it falls within the accepted range.
while (stop < 0 || stop > 50 || start > stop)
{
// If it doesn’t, the program should tell the user that
// their input wasn’t in the accepted range and
cout << "Please enter a value from " << start << " to 50\n";
// ask the user to reenter a value within the range.
cout << "Stop value: ";
cin >> stop;
}
// Once both values are determined to be within the accepted range
//looping from start to stop value
for (int i = start; i <= stop; i++)
//adding each value with sum
sum += i;
//printing out the sum
cout << "Sum: " << sum << endl;
return 0;
}
.
Output:
.