Homework Help - Series Program

Write a function that returns the value of the following series.
f(n, y) = (1/y)( 2 + 1/3 + 4 + 1/5 + 6 + 1/7 + ... + x )
where the values n is the number of terms and y is a multiplication coefficient. Both n and y are supplied by the user and passed to the function. The main function should continue to query the user for values of n and y and print the result until the y is entered as a zero.

This is what i currently have but I am very confused and not too sure where to go from here. Thanks

#include <iostream>
#include <string>
#include <cmath>

using namespace std;

float function(int,double);

int n;
double x;

int main(void)

cout<<"Enter the value for x:";
if (x !=0)
cout<<"Enter the number of terms : ";
cout<<"\nSUM = "<<function(n,x)<<endl;
return 0;
float function(int n, double x)
double func = 0.0;
float sum = 0.0;

for(int i=1;i<=n;i=i+1)
for(int j=0;j<=n;j=j+1)
func = (1/x)*(2*i+(1/(j+2)));

return func;
There is something called recursion in which a function calls itself from within its own definition block.
Think about what the pattern is in the series and come up with a way to apply that with recursion. Remember to come up with a way to break out of the recursion or you'll end up with an infinite loop that will eventually crash the program.

Example of recursion:
double SimpleSummation(double start, double rate){
      if(rate > 0.0001)   return start*rate + SimpleSummation(start,rate-0.15);
      else return 0;

Hint: You might need pow().

Just noticed that you also need the main function to continue asking the user for new n and y values. You can wrap your input and function call within a loop.
Last edited on
Topic archived. No new replies allowed.