Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

in C++ why am i not geting the desired ouput write a recursice function to compu

ID: 3840986 • Letter: I

Question

in C++ why am i not geting the desired ouput

write a recursice function to compute the following series:

m(i)=1/3+2/5+3/7+4/9+4/11+6/13........+i/2i+1

this is my code below

#include <iostream>

using namespace std;

double m(int j);

int main()

{

for (int i =1; i<11; i++)

cout <<" i = "<<i<<","<<"the sum of series = "<<m(i)<<endl;

  

cout<<endl;

return 0;

}

double m(int j)

{

if (j==1)

   return (j/3);

else

return (j/3.0)+(j/(2.0*j+1));

}

i want to get

i=1, sum of series =0.33333333

i=2, sum of series = 0.7333333

i=3,sum of series=1.16190

....................

i=10,sum of series =4.40956

Explanation / Answer

Modified Code:

#include <iostream>
using namespace std;
// m(i)=1/3+2/5+3/7+4/9+4/11+6/13........+i/2i+1

// function declaration

double m(double j);
int main()
{
for (double i=1; i<11; i++)
cout <<" i = "<<i<<","<<"the sum of series = "<<m(i)<<endl;
  
cout<<endl;
return 0;
}

double m(double j)
{
static double sum = 0;
  
// base condition
if (j==1)
return (j/3);
else
// recursive step
return m(j-1) + (j/(2*j +1));

// summing the series of series. sum will be zero only for first time after that last value gets added   
sum += m(j);
  
return sum;
}


Execution and output:
i = 1,the sum of series = 0.333333
i = 2,the sum of series = 0.733333
i = 3,the sum of series = 1.1619
i = 4,the sum of series = 1.60635
i = 5,the sum of series = 2.06089
i = 6,the sum of series = 2.52243
i = 7,the sum of series = 2.9891
i = 8,the sum of series = 3.45969
i = 9,the sum of series = 3.93337
i = 10,the sum of series = 4.40956


Explanation:
There are couple of problems i have found in your code. Following are the details.
a) Since we are dealing with fractions you should be treating each number as float or double but not int. Thats why i have changed the function argument of m as double so we can have floating point values.
b) There is a base condition(mentioned in the code) in your code but no recursive step. Thats why you are not seeing series summed up properly. When i said recursive step, the function should be calling itself so that the iterative process of summing the series should be taken care. Always remember that a recursive code must have a base condition and recursive step. Otherwise it is not useful and cannot be called as recursion.

On another note i have declared sum as static variable so that it would be initialized to zero only for the first time and after that the last value gets added.