Solve the following problem by showing the design of your solution as an algorithm.
The problem – The program will take two integers from the user, say n1 and n2. It will then print the sum of all numbers between n1 and n2, inclusive. For example, if the user enters 5 and 9, the program will print the value of 5+6+7+8+9. On the other hand, if the user enters 5 and -2, the program will print the value of 5+4+3+2+1+0+(-1)+(-2). Note: Do not assume the user will always enter the smaller number first.
#include <iostream>
using namespace std;
int main() {
int n1, n2;
int start, end;
cin >> n1 >> n2;
if (n1 <= n2) {
start = n1;
end = n2;
}
else {
start = n2;
end = n1;
}
int sum = 0;
for (int i=start; i<=end; i++) {
sum += i;
}
cout << sum;
return 0;
}
Comments
Leave a comment