views:

698

answers:

7

Now that I am using recursion to calcuate the sum of numbers, I want to do something slightly different. The following is my code that will sum the numbers 1,2,3,4,5. How would I modify my code to place the numbers 1, 2, 3, 4, 5 into an array and then use it in the recursion method? I have tried so many different attempts and I am apparently missing something. I know that in the recursion method, that I want to use the Length property of the array to control it.

Susan

   static void Main(string[] args)
    {
        Console.WriteLine(Sum(5));
        Console.Read();
    }

    static int Sum(int value)
    {
        if (value > 0) 
        {
            return value + Sum(value - 1);
        }
        else
        {
            return 0;
        }
    }
+2  A: 

Sniff, sniff, smells like homework to me.

However, a hint. Adding all the elements of an array of length 'n' is the same as adding all the elements of an array of length 'n-1', then adding the value of element 'n'.

The result of adding all the elements of an array of length '1' is just the value of the one element

Paul
+1  A: 

I believe that you need to pass the array and the index in your Sum function to control the recursivity.

Daniel
+2  A: 

What about using a Stack?:

Stack<int> stack = new Stack<int>(new int [] {1,2,3,4,5});
Console.WriteLine(SumStack(stack));

public static int SumStack(Stack<int> input)
{
    return input.Count > 0 ? input.Pop() + SumStack(input) : 0;
}
CMS
Too many new concepts error. ;-)
Tomalak
A: 

You're wanting to perform an operation that is commonly referred to as "fold" a.k.a. "reduce".

Luckily, the .NET team did your (home)work for you!

    static int sum(int[] values)
    {
        return values.Aggregate<int>((hd, tl) => hd + tl);            
    }

You can rewrite it for easier readability if you like. ;)

EDIT: usage example

int[] values = new int[]{1,2,3,4,5};
Console.WriteLine(sum(values));
dss539
Since System.Array implements IEnumerable, you don't need to convert the array to List, and the type parameter of the Aggregate method, can be inferred by the compiler: return values.Aggregate((hd, tl) => hd + tl);
CMS
Doh, you're absolutely right. Not sure what I was thinking there. Edited to reflect your point.
dss539
A: 

Of if your no good with lambda expressions or you only have .net 2.0, this is simple enough;

static void Main(string[] args)
{

    int[] myArray = new int[5] {1,2,3,4,5 };

    Console.WriteLine(Sum1(myArray));
    Console.Read();

}

private static int Sum1(int[] myArray)
{

    if (myArray.Length > 0)
    {
        int lengthZeroAdjusted = myArray.Length - 1;
        int element = myArray[lengthZeroAdjusted];

        Array.Resize<int>(ref myArray, lengthZeroAdjusted);
        return element + Sum1(myArray);
    }
    else
    {
        return 0;
    }
}
So in this method, we are passing the array myArray. Then we are setting the lengthZeroAdjusted to myArray.Length - 1 which would be 5 - 1 (4). So what exactly is the following line used for: Array.Resize<int>(ref myArray, lengthZeroAdjusted);Susan
Hi there Susan :)I think you needed something along the same lines as your initial example so as to ease understanding. I am assume as others here have, you might be new to programming. Apologies if your not.So that the function remains faithful to the type 'array' that you asked about, i simply maintained the type. By doing so we deal with the array type slightly differently than some of the other suggestions.
To describe what's needed verbosely , so that all the function takes is an array, it must be that we modify the array each time we recurs. Similar to the stack http://en.csharp-online.net/Generic_Stack functionally. We take the last value in the array and store it in element, we can now reduce the size of the array by 1, by passing lengthZeroAdjusted in which will always be 1 less than myArray.
For each recursion the array becomes one less, and the value of element becomes the last element of the *new* array.So, Array.Resize is a function that will copy all the elements from one array to another new array which is smaller by 1, so for each recursion the last element is effectively deleted.
A possibly faster method would be to perform this with something called bit shifting rather than array copying. If the function were a generic function, we could pass in an array of int32 which would subsequently convert to an array of bytes. The bytes could be shifted 32 bits MSB at each recursion. that's a challenge for you. Bar in mind that recursion is not performant for a reduction operation, but if that's your task then that's 'another' way of doing this.
sorry this site only allows 500 chars for a reply... odd stuff, mean perhaps.
Array.Resize<T> Method http://msdn.microsoft.com/en-us/library/bb348051.aspx
+5  A: 
let seq = [1;2;3;4;5]

let rec samp nums = 
  match nums with
  | []      -> 0
  | h::t    -> h + samp t
JP Alioto
I like this one. Totally non-believable for the OP to submit this as the homework answer, given the level of experience shown the original question :)
Paul
I wanted to give her a hint, without giving her the answer :)
JP Alioto
OK, I bite. Out of curiosity, for my culture, what language is it? Some functional language for sure, but there are so many... :-)
PhiLho
It's F# ... http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/
JP Alioto
A: 

Recursion essentially means doing the small part, and giving the larger part to somebody else. Now if you have to 'n' elements of array, you ask somebody to give you sum of last n-1 elements, and just first one yourself ... just handle the case where there is nothing to be done ...

a pseudo code would be :

   sum array start_index   =  if ( start_index >= length(array) ) return 0
                              else return array[start_index] = sum array (start_index + 1)

   print (sum array 0 )
Vardhan Varma