Sum parameter in variable params - CSharp Custom Type

CSharp examples for Custom Type:Method Parameter

Description

Sum parameter in variable params

Demo Code

using System;/*from   w ww . ja  va 2s  .  com*/
class SumCalculator
{
   public static void Main()
   {
      int result1, result2, result3, result4, result5;
      int[] myNumbers = {4, 10, 6, 8, 2};
      result1 = Sum(3,5);
      result2 = Sum(10,20,30);
      result3 = Sum(1,2,3,4,5,6,7,8,9,10);
      result4 = Sum(myNumbers);
      result5 = Sum();
      Console.WriteLine("\nEnd results: {0}, {1}, {2}, {3}, {4}", result1, result2, result3, result4, result5);
   }
   public static int Sum(params int[] numbers)
   {
      int sum = 0;
      Console.Write("\nThe numbers array contains {0} elements:", numbers.Length);
      foreach (int number in numbers)
      {
         Console.Write(" {0}", number);
         sum += number;
      }
      Console.WriteLine("\nThe sum is: {0}", sum);
      return sum;
   }
}

Result


Related Tutorials