Answer to Question #181783 in C++ for tan

Question #181783

Write a function named "sum_from_to" that takes two integer arguments, call them "first" and "last", and returns as its value the sum of all the integers between first and last inclusive. Thus, for example:

cout << sum_from_to(4,7) << endl;  //will print 22 because 4+5+6+7 = 22

cout << sum_from_to(-3,1) << endl; //will print -5 'cause (-3)+(-2)+(-1)+0 +1 = -5

cout << sum_from_to(7,9) << endl;  //will print 22 because 7+8+9 = 24

cout << sum_from_to(9,9) << endl;  //will print 9

1
Expert's answer
2021-04-17T19:23:38-0400
#include <iostream>
using std::cout;
using std::endl;
int sum_from_to(int first, int last)
{
    if (first > last) 
    {
        cout << "Incorrect values entered";
        return NULL;
    }
    int sum = 0;
    for (int i = first; i <= last; i++) 
    {
        sum += i;
    }
    return sum;
}


int main()
{
    //test function
    cout << sum_from_to(4, 7) << endl;  //will print 22 because 4+5+6+7 = 22
    cout << sum_from_to(-3, 1) << endl; //will print -5 'cause (-3)+(-2)+(-1)+0 +1 = -5
    cout << sum_from_to(7, 9) << endl;  //will print 22 because 7+8+9 = 24
    cout << sum_from_to(9, 9) << endl;  //will print 9
    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
APPROVED BY CLIENTS