Exercise
Function Sum Of Array
Objective
Write a C# program to calculate the sum of the elements in an array. "Main" should be like this:
public static void Main()
{ int[] example = {20, 10, 5, 2 };
Console.WriteLine(
__"The sum of the example array is {0}", __Sum(example));
}
}
Write Your C# Exercise
C# Exercise Example
// Importing the System namespace to access basic system functions
using System;
class Program
{
// Function to calculate the sum of all elements in the array
public static int Sum(int[] array)
{
// Initialize a variable to store the sum of array elements
int total = 0;
// Loop through each element of the array and add it to the total sum
foreach (int number in array)
{
total += number;
}
// Return the calculated sum
return total;
}
// Main method where the Sum function is called
public static void Main()
{
// Define an example array with integer values
int[] example = { 20, 10, 5, 2 };
// Call the Sum function to calculate the sum of the array elements
// Then display the result using Console.WriteLine
Console.WriteLine("The sum of the example array is {0}", Sum(example));
}
}