Programming Course in C# ¡Free!

Function sum of array

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise


public static void Main()
{
    int[] example = {20, 10, 5, 2 };


    Console.WriteLine( "The sum of the example array is {0}",
        Sum(example));

Output



Solution


using System;
public class SumArray
{
public static int Sum(int[] example)
{
int total=0;
for (int i = 0;i < example.Length; i++)
total += example[i];
return total;
}

public static void Main()
{
int[] example = {20, 10, 5, 2 };
Console.WriteLine("The sum of the example array is {0}", Sum(example));
}
}