In: Computer Science
Write a function in C# that takes an array of double as the parameter, and return the average
For this we would need 2 methods first to calculate the sum,
public double Sum(params double[] arr)
{
double result = 0.0;
for(int i = 0; i < arr.Length; i++)
{
result += arr[i];
}
return result;
}
and another one to calculate the average using the sum method listed above.
public double Average(params double[] arr)
{
double sum = Sum(arr);
double result = (double)sum / arr.Length;
return result;
}
The full code is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public double Sum(params double[] arr)
{
double result = 0.0;
for(int i = 0; i < arr.Length; i++)
{
result += arr[i];
}
return result;
}
public double Average(params double[] arr)
{
double sum = Sum(arr);
double result = (double)sum / arr.Length;
return result;
}
public static void Main(string[] args)
{
double[] values={1.0,2.0,3.0,2.3};
Console.WriteLine("Hello, world!");
Console.WriteLine(values.Average());
}
}
}