Given two integers, start and end , where end is greater than start , write a recursive C++ function that returns the sum of the integers from start through end , inclusive.
Expert Answer
#include<iostream>
using namespace std;
//a recursive function to sum.from start to end inclusive
int recursive_sum(int start,int end)
{
if(start == end)
return end;
return recursive_sum(start+1,end)+start;
}
int main()
{
int start,end;
//taking input from keyboard
cout<<“Enter integer (start):”;
cin>>start;
cout<<“Enter integer (end : should be greater than stop)”;
cin>>end;
int sum;//variable to store sum from start to end inclusive
//calling a recursive function to sum.from start to end inclusive
sum = recursive_sum(start,end);
cout<<“Sum is:”<<sum<<“n”;
return 0;
}
output:
Enter integer (start):1
Enter integer (end : should be greater than stop)5
Sum is:15
Process exited normally.
Press any key to continue . . .