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 = 2
cout << sum_from_to(9,9) << endl; //will print 9
int sum_from_to(int first, int last)
{
int i;
int res = 0;
for(i = first; i < last+1; ++i )
res += i;
return res;
}
Comments
Leave a comment