Here is code in C++.
#include <bits/stdc++.h>
using namespace std;
// recursive function to calculate sum from 1 to n
int calculate_sum(int n)
{
if (n <= 1)
return n;
return n + calculate_sum(n - 1);
}
// Driver code
int main()
{
// variable to read input
int n;
cout<<"Please Enter a number: ";
//reading input from user
cin>>n;
do{
if(n<=0)
{
cout<<"please enter only positive numbers(greater than 0):"<<endl;
cin>>n;
}
} while(n<=0);
// calling the recursive function and printing the sum
cout << "Sum of all numbers from 1 to "<<n<<" is: "<<calculate_sum(n);
return 0;
}
Step-by-step explanation:
Read input from user and assign it to variable "n".if the input is less
than or equal to 0, it will again ask user to enter a number greater than 0.
then Call function calculate_sum() with argument "n". This function will
calculate sum recursively from n to 1.when recursive function call itself for
n<=1 (base condition),it calculate the total sum.
Output:
Please Enter a number: -5
please enter only positive numbers(greater than 0):
6
Sum of all numbers from 1 to 6 is: 21