Computer Science, asked by Aspect98021, 5 months ago

write a recursive function called m(i) to compute the following series m(i)= 1 + 1/2 +1/3+....+1/i
Demonstrate the function by calling it in a loop that displays m(i) for i = 1,2,3,.....,10
Program for the language c++

Answers

Answered by anindyaadhikari13
5

\textsf{\large{\underline{Solution}:}}

The given problem is solved using language - C++.

#include <iostream>

using namespace std;

double m(int n){

   if(n==1)

       return 1.0;

   return 1/(double)n + m(n-1);

}

int main() {

   cout<<"Enter limit - ";

   int n;

   cin>>n;

   cout<<"Sum is: "<<m(n);

   return 0;

}

\textsf{\large{\underline{Explanation}:}}

Here we have created a recursive function m() which calculates the sum of the series. Recursive function is a function which calls itself. It must have a base case which is used to terminate the recursion.

In mathematical representation, we can write the function as,

\sf\implies m(i)=\begin{cases}\sf\dfrac{1}{i}+m(i-1)\ if\ i&gt;1\\ \sf 1\ if\ i=1 \end{cases}

Hence, the problem is solved.

See the attachment for output.

Attachments:
Similar questions