119k views
3 votes
Write a method that accepts an integer argument and returns the sum of all the integers from 1 up to (and including) the number passed as an argument. For example, if 3 is passed as an argument, the method will return the sum of 1+2+3, which is 6. Use recursion to calculate the sum. Test your method in main by prompting the user to enter a positive integer to sum up to. Provide input validation so that only positive values are accepted.

User Jassin
by
5.4k points

1 Answer

4 votes

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

User Nashcheez
by
5.6k points