Write a recursive function named “sum” with one input parameter, an integer n. T
ID: 3838953 • Letter: W
Question
Write a recursive function named “sum” with one input parameter, an integer n. The function returns the sum of numbers 1, 2, 3… n. Test the function in the main function, prompt the user to input the value for n, and output the result after calling the recursive function. Write a recursive function named “sum” with one input parameter, an integer n. The function returns the sum of numbers 1, 2, 3… n. Test the function in the main function, prompt the user to input the value for n, and output the result after calling the recursive function. Write a recursive function named “sum” with one input parameter, an integer n. The function returns the sum of numbers 1, 2, 3… n. Test the function in the main function, prompt the user to input the value for n, and output the result after calling the recursive function.Explanation / Answer
#include<iostream>
using namespace std;
int sum(int n);
int main()
{
int n;
cout << "Enter integer: ";
cin >> n;
cout << "Sum of numbers from 1 to " <<n<<" :"<< sum(n);
return 0;
}
int sum(int n)
{
if(n != 0)
return n + sum(n - 1);
return 0;
}