C# Program to Calculate the Sum of the Elements in an Array

This C# program defines a function called Sum that calculates the sum of the elements in an array. The Main method initializes an array with specific integer values and then calls the Sum function to calculate the sum of those values. The result is displayed on the screen using Console.WriteLine. This program helps in understanding how to process arrays and perform basic arithmetic operations such as summing elements.



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

 Copy 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

Share this C# Exercise

More C# Practice Exercises of Functions in C#

Explore our set of C# Practice Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C#.