Write a recursive function in C++ that computes the sum of all numbers from 1 to n, where n is given as parameters.
Solution:
#include <iostream>
using namespace std;
int sum(int);
int main()
{
int x; cout << "Write a number, I'll tell u sum of all numbers from 1 to your number: "; cin>>x;
cout << "\nSum of all numbers from 1 to " << x << " is: " << sum(x) << endl;
}
int sum(int x)
{
if (x==1)
return 1;
else
return x+sum(x-1);
}
Solution:
#include <iostream>
using namespace std;
int sum(int);
int main()
{
int x; cout << "Write a number, I'll tell u sum of all numbers from 1 to your number: "; cin>>x;
cout << "\nSum of all numbers from 1 to " << x << " is: " << sum(x) << endl;
}
int sum(int x)
{
if (x==1)
return 1;
else
return x+sum(x-1);
}
Oh man you saved my life
ReplyDelete