Click here to Skip to main content
15,897,226 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I did this but it is returning the value of n. Tell me what to do???

int sum_of_series(int n)
{
static int value = 0;
static int answer;
static int answer1;
if(n == 1)
{
return 1;
}
else
{
answer = 1/1+sum_of_series(n-1);
return answer;
}
//return value;
}
Posted
Comments
Mohibur Rashid 11-Jan-15 2:21am    
Your logic is wrong.One example is 1/1 will always return 1

Um. Have you looked at your code?
C++
answer = 1/1+sum_of_series(n-1);

Operator precedence says that is:
C++
answer = (1/1)+sum_of_series(n-1);
since you want:
1+1/2-1/3+1/4...
you need to start by using 1/N at some point... Then you can worry about the sign changing...
 
Share this answer
 
C#
public double sum_of_series(int n)
     {
         //the condition where recursion stops
         if (n == 1)
         {
             return 1;
         }
         double result;
         //if the divisor is even, sum the result else subtract it.
         if (n % 2 == 0)
         {
             result = this.sum_of_series(n - 1) + 1 / (double)n;
         }
         else
         {
             result = this.sum_of_series(n - 1) - 1 / (double)n;
         }

         return result;
     }
 
Share this answer
 
Comments
George Swan 12-Jan-15 12:12pm    
I'm keen to improve my coding so I would be most grateful if the guy who down-voted this solution could please explain the reason why.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900