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
#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
}
Comments
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.
please help me
Leave a comment