tags:

views:

132

answers:

3

In C#, how do I make a static method called Sum that takes one parameter of int array type and returns the sum of its parameter's elements? And what are ways to get the sum other than return Sum()?

+10  A: 

You'd start by creating an int variable with a value of 0, say x, iterating over the array and adding each of the values to x, then returning x.

Though you really need to start paying attention in class, cause this is basic stuff.

Ashley Williams
If he illiterates over the array, how will he be able to read the values?
Larry Lustig
Embarrassingly, I actually had to google "* over the array" to find the correct word…
Ashley Williams
+1 for answer, and mentioning the need to pay attention. I think most of us would agree that 'homework' questions are OK... when someone really seems to have tried and is actually stumped about something they've put effort into. This is so basic, I wonder if the next question will be "how do I create a variable?"
Andrew Barber
Wow the people in this forum are really rude, they expect everyone to be on the same level... unbelievable. Who cares if its the most basic of knowledge to you... If you're gonna help then help, if not go else where. I thought the point of this site was to help each other out, not to insult others because of their lack of ability to measure up to one's own standards. Thanks ashleyw.
Morex
I think the point people are trying to make is that you've marked this as a homework question, which people are always more than happy to *help* with, but it's the kind of thing which is taught in the first few sessions of any programming course. So if you're truly having difficulty grasping homework tasks like this, I'd recommend you speak with your teacher.
Ashley Williams
Get off your high horse Morex. This site is full of tens of thousands of people who want to help each other out, regardless of anyone's level. The only ability that you're lacking is being able to take 2 minutes to help yourself out by reading the first chapter of your textbook.
anthony
I think, @Morex, that the general perception is that you didn't work on this question at all before asking for a solution here.
Larry Lustig
Its not wasting anyone's time, I'm assuming that's what you got on here to do is answer questions. If you think its a waste, no one is making you answer a question. If anything is a waste look at what you just posted, now what good did it do other than **waste** your own time?
Morex
@Larray Lustig: Indeed, particularly since this is a follow-up question to Mark Byers' considerate response, here: http://stackoverflow.com/questions/4038541/i-need-help-writing-a-c-program-closed
@Larry, It's just that I'm a bit confused about the whole question.
Morex
@Morex: What I'd do if I were you, is go away and spend some quality time with Google, your textbooks, and text editor, and try your best to complete the task. Programming is frustrating at times for even the best of developers, but you'll solve the problem in the end, and will have learnt a ton in the process.
Ashley Williams
This is really unnecessarily complicated. There is no need for loops or variables or mutable state here. It's just a simple fold.
Jörg W Mittag
Yours may take a few less lines to implement, but takes 3,000+ more characters to explain. And `reduce` methods aren't magic, they'll all have loops somewhere down the stack, and use memory for temporary variables, so I don't really see how it's "unnecessarily complicated" to show Morex the simplest implementation of his problem.
Ashley Williams
+2  A: 

I think this classic article will help you at your first step of programming: http://www.catb.org/esr/faqs/smart-questions.html

Feil
+1 Gorgeous. Bookmarked. Thank you.
A: 

Obviously, we won't do your homework for you, but here is a little hint: computing the sum of the elements of a collection is an instance of a more general pattern: reducing a sequence of things down to a single thing.

This idea of taking a sequence of things and reducing it down to a single thing has different names in different cultures. The most common name is "folding". It is also known as "reducing", "aggregating" or "accumulating". In mathematical category theory, it is known as a "catamorphism" (and no, I don't know what that means, either).

Pretty much every programming language provides a ready-made implementation of this concept. In the Smalltalk programming language, the method which implements this is called inject:into:, in Ruby it is called inject or reduce, in PHP array_reduce, in Haskell foldl or foldr (depending on whether it folds from left to right or right to left) or foldl1, foldr1 (meaning that it uses the first element of the sequence instead of a user-supplied value as the starting value), in Scala foldLeft, foldRight or reduceLeft, reduceRight (depending on whether you supply the initial value or it simply uses the first element of the sequence), in C++ it is called std::accumulate, ECMAScript calls it reduce / reduceRight.

C# also has it, but I'm going to leave a little work for you.

There is a nice way to visualize what this "fold" does: you can simply think of it as replacing the commas in a sequence with a function of your choosing.

So,

fold + [1, 2, 3]

Basically means, take the sequence

1, 2, 3

and replace all commas with +:

1 + 2 + 3

And that's how easy it is to compute the sum of an array.

Here are couple of examples in different programming languages to help you along.

Let's start with the simplest and IMHO most beautiful one: Haskell:

sum = foldl1 (+)

Yup, that's all there is to it. That's the complete implementation of a sum function, which sums a list (Haskell prefers lists over arrays) of integers. It simply says "summing a list is just folding using the + function".

Use it like so:

sum [1, 2, 3]

In Scala, it is almost as nice:

def sum(nums: Traversable[Int]) = nums reduceLeft { _ + _ }

Note that this function is actually much more general: it works for any Traversable collection, not just for arrays.

Here's how to use it:

sum(Array(1, 2, 3))

Ruby:

def sum(nums)
  nums.reduce(:+)
end

Again, this is much more general, since it works with any Enumerable collection.

Use like this:

sum([1, 2, 3])

Here's ECMAScript:

function sum(nums) {
    return nums.reduce(function (acc, el) { return acc + el; });
}

And the usage:

sum([1, 2, 3]);

C++:

int sum(vector<int> nums) {
    return std::accumulate(nums.begin(), nums.end(), 0);
}

Note that I don't actually tell it what to use to fold the vector. That's because + is the default. If you wanted to make it explicit, you'd use:

int sum(vector<int> nums) {
    return std::accumulate(nums.begin(), nums.end(), 0, std::plus<int>);
}

Usage:

std::vector<int> v = { 1, 2, 3 };
sum(v);

Last but not least, here's C#:

static int Sum(int[] nums)
{
    return nums.Sum();
}

Yep, that's right: there already is a Sum method for arrays (or more precisely an extension method for IEnumerables).

Use it like so:

Sum(new int[] { 1, 2, 3 });

However, if you feel that this is cheating, then there is also an implementation of folding in C# (or more precisely the BCL). I won't tell you its name, but you will recognize it as soon as you see it.

Jörg W Mittag
When you wrote this, did you really think the lazy would even bother skim it? He wouldn't even have asked the question if he would read.
Kinderchocolate
+1 for making something simple WAY complex. That is the best thing since I had to prove 1+1 =2 in number theory. Bravo.
Byron Whitlock