Declare methods for calculating the sum average maximum and
Declare methods for calculating the sum, average, maximum, and minimum of the list. Their implementation should be straightforward.
I need help creating the methods to calculate the above. It is for a list in c#.
Solution
using System;
using System.Collections.Generic;
class MainClass {
public static void Main (string[] args) {
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(6);
Console.WriteLine($\"Sum : {sum(numbers)}\");
Console.WriteLine($\"Average : {average(numbers)}\");
Console.WriteLine($\"Maximum : {maximum(numbers)}\");
Console.WriteLine($\"Minimum : {minimum(numbers)}\");
}
/* add all the numbers and return sum */
public static int sum(List<int> numbers){
int s = 0;
foreach(int num in numbers){
s += num;
}
return s;
}
/* find the sum of given numbers and divide by numbers Count */
public static double average(List<int> numbers){
double s = sum(numbers);
return s/numbers.Count;
}
/* Loop through the numbers and find the maximum */
public static int maximum(List<int> numbers){
int max = numbers[0];
for(int i=1;i<numbers.Count;i++){
if(numbers[i]>max)
max = numbers[i];
}
return max;
}
/* Loop through the numbers and find the minimum */
public static int minimum(List<int> numbers){
int min = numbers[0];
for(int i=1;i<numbers.Count;i++){
if(numbers[i]<min)
min = numbers[i];
}
return min;
}
}
/*
*/
