w3resource

C#: Compute the sum of the elements of an given array of integers


C# Sharp Basic Algorithm: Exercise-91 with Solution

Write a C# Sharp program to compute the sum of the elements of an array of integers.

Visual Presentation:

C# Sharp: Basic Algorithm Exercises - Compute the sum of the elements of an given array of integers.

Sample Solution:-

C# Sharp Code:

using System; // Importing the System namespace

namespace exercises // Defining a namespace called 'exercises'
{
    class Program // Defining a class named 'Program'
    {
        static void Main(string[] args) // The entry point of the program
        {
            // Output the result of the 'test' function with different integer arrays as arguments
            Console.WriteLine(test(new[] { 10, 20, 30, 40, 50 })); // Calling test method with array [10, 20, 30, 40, 50] and displaying the result
            Console.WriteLine(test(new[] { 10, 20, -30, -40, 50 })); // Calling test method with array [10, 20, -30, -40, 50] and displaying the result
        }     

        // Method to calculate the sum of the first five elements of an integer array
        public static int test(int[] a1)
        {
            // Return the sum of the first five elements of the array 'a1'
            return a1[0] + a1[1] + a1[2] + a1[3] + a1[4];
        } 
    }
}

Sample Output:

150
10

Flowchart:

C# Sharp: Flowchart: Compute the sum of the elements of an given array of integers.

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# Sharp program to check two given arrays of integers of length 1 or more and return true if they have the same first element or they have the same last element.
Next: Write a C# Sharp program to rotate the elemets of a given array of integers (length 4) in left direction and return the new array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/csharp-exercises/basic-algo/csharp-basic-algorithm-exercises-91.php