Answer to Question #318321 in C++ for Beki

Question #318321

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.

1
Expert's answer
2022-03-25T15:11:45-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog