Develop a C++ program to calculate sum of square root from 1 to n numbers using recursive functions
#include <cmath>
#include <iostream>
using namespace std;
double sum_sqrt(int n)
{
double res = sqrt((double)n);
if (n > 1)
{
res += sum_sqrt(n - 1);
}
return res;
}
int main()
{
int num;
cout << "Enter a number: ";
cin >> num;
if (num >= 0)
{
cout << "Sum of square roots from 1 to " << num << " is " << sum_sqrt(num);
}
else
{
cout << "Cannot calculate the square root of negative number.";
}
}
Comments
Leave a comment