Group
Functions in C#
Objective
1. Define a function called Sum that accepts an integer array as a parameter.
2. Inside the Sum function, calculate the sum of all elements in the array.
3. In the Main method, define an integer array (e.g., {20, 10, 5, 2}).
4. Call the Sum function and pass the array to calculate the sum.
5. Use Console.WriteLine to display the sum in a formatted string.
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));
}
Example C# Exercise
Show C# Code
using System;
class Program
{
// Main method where the program execution begins
public static void Main()
{
// Define an example array with some values
int[] example = { 20, 10, 5, 2 };
// Call the Sum function and display the result
Console.WriteLine("The sum of the example array is {0}", Sum(example));
}
// Function to calculate the sum of the elements in an integer array
public static int Sum(int[] array)
{
// Initialize a variable to store the sum
int sum = 0;
// Loop through each element in the array and add it to the sum
foreach (int number in array)
{
sum += number; // Add the current number to the sum
}
// Return the total sum
return sum;
}
}
Output
The sum of the example array is 37