CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com

#### Hybrid View

1. Junior Member Join Date
Aug 2009
Posts
1

## Using recursion to add odd numbers

Hi Friends,

I am trying to write a method to calculate the sum of the odd numbers in all the numbers less than the given number. so eg. CalcOdd(7) would return 5 + 3 + 1 = 9. CalcOdd (10) would return 9 + 7 + 5 + 3 + 1 = 25 etc

The method needs to take in a number, subtract 1, then recursively work backwards adding all odd numbers until it reaches 0. This is what I have so far.

private static int CalcOdd(int n)
{

if (n <= 1)
return 1;
else
if (n % 2 == 0)
n--;

return n + CalcOdd(n - 2);
}

It doesn't work so well, it includes the number passed in in the addition which is not what I want. Can anyone suggest a better way of doing this ? I would also loke to be able to port the answer to work for even numbers and add the option to include the original passed in number in the answer.

Many thanks  Reply With Quote

2. ## Re: Using recursion to add odd numbers

i revised the code a little for you:

Code:
```using System;
using System.Collections.Generic;
using System.Text;

namespace Recursive
{
class Program
{
static void Main(string[] args)
{

Console.WriteLine(y);

}

{

int z;
if (n &#37; 2 == 0)
{
}
else
{
}

return z;

}

{

if (n == 1)
return 1;

return n + oddAddRecursive(n - 2);
}

}
}```  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
• 