Common Array Operations
Part of the Fundamentals section of Coddy's C# journey — lesson 66 of 69.
Here are some common array operations:
- Find the sum of all elements in an array:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
foreach (int number in numbers) {
sum += number;
}
Console.WriteLine("Sum: " + sum);- Find the average of elements in an array:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
foreach (int number in numbers) {
sum += number;
}
double average = (double) sum / numbers.Length;
Console.WriteLine("Average: " + average);- Find the maximum element in an array:
int[] numbers = {1, 5, 2, 9, 3};
int max = numbers[0];
for (int i = 1; i < numbers.Length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
Console.WriteLine("Max: " + max);- Find the minimum element in an array:
int[] numbers = {1, 5, 2, 9, 3};
int min = numbers[0];
for (int i = 1; i < numbers.Length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
Console.WriteLine("Min: " + min);Challenge
EasyCreate a method named CalculateStats that takes an array of integers as input and performs the following operations:
- Calculates the sum of all elements in the array.
- Calculates the average of the elements in the array.
- Finds the maximum element in the array.
- Finds the minimum element in the array.
The method should return an array of doubles containing the sum, average, maximum, and minimum, in that order.
Try it yourself
using System;
public class Program {
public static double[] CalculateStats(int[] arr) {
// Write your code here
}
public static void Main(string[] args) {
string text = Console.ReadLine();
string[] arrString = text.Split(",");
int[] numbers = new int[arrString.Length];
for (int i = 0; i < arrString.Length; i++) {
numbers[i] = int.Parse(arrString[i]);
}
double[] stats = CalculateStats(numbers);
Console.WriteLine("Sum: " + stats[0]);
Console.WriteLine("Average: " + stats[1]);
Console.WriteLine("Maximum: " + stats[2]);
Console.WriteLine("Minimum: " + stats[3]);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic Shortcuts5Operators Part 2
Comparison OperatorsLogical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3