dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Using recursion to add odd numbers

  1. #1
    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

  2. #2
    Join Date
    Mar 2008
    Location
    IRAN
    Posts
    811

    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)
            {
    
                int y = oddAdd(9);
                Console.WriteLine(y);
    
                Console.ReadKey(true);
            }
    
    
            static int oddAdd(int n)
            {
    
                int z;
                if (n &#37; 2 == 0)
                {
                    z = oddAddRecursive(n - 1);
                }
                else
                {
                    z = oddAddRecursive(n - 2);
                }
    
                return z;
    
            }
    
               static int oddAddRecursive(int n)
               {
    
                   if (n == 1)
                       return 1;
    
                   return n + oddAddRecursive(n - 2);
               }
    
        }
    }
    Please rate my post if it was helpful for you.
    Java, C#, C++, PHP, ASP.NET
    SQL Server, MySQL
    DirectX
    MATH
    Touraj Ebrahimi
    [toraj_e] [at] [yahoo] [dot] [com]

Posting Permissions

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


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)