Answer to Question #181703 in C++ for Darren

Question #181703

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-19T01:39:55-0400
#include<bits/stdc++.h>
using namespace std;
int sum_from_to(int first, int last)
{
    int s=first;
    while(first<last)
    {
        first=first+1;
        s=s+first;
    }
    return s;
}
int main()
{
    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
}

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

Assignment Expert
15.04.21, 14:08

Dear Darren, Questions in this section are answered for free. We can't fulfill them all and there is no guarantee of answering certain question but we are doing our best. And if answer is published it means it was attentively checked by experts. You can try it yourself by publishing your question. Although if you have serious assignment that requires large amount of work and hence cannot be done for free you can submit it as assignment and our experts will surely assist you.

Darren
15.04.21, 10:57

please help me

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS