Question

Write a recursive function named arithmeticSum that takes a positive integer parameter n and returns the...

Write a recursive function named arithmeticSum that takes a positive integer parameter n and returns the sum of the integer numbers from 1 to n Please write in C++

0 0
Add a comment Improve this question Transcribed image text
Answer #1


#include <bits/stdc++.h>
using namespace std;

int arithmeticSum(int n) { // recursive function
if(n<0){
return -1; //negative no not allowed
}
if(n == 0) { //base case
return n;
}
return n + arithmeticSum(n-1); //recursive call
}

int main()
{
int n, sum=0;
cout<<"Enter n: "<<endl;
cin>>n;
sum = arithmeticSum(n);
if(sum == -1) {
cout<<"Negative numbers not allowed"<<endl;
} else {
cout<<"Sum of numbers from 1 to "<<n<<": "<<sum;
}
}

Add a comment
Know the answer?
Add Answer to:
Write a recursive function named arithmeticSum that takes a positive integer parameter n and returns the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT