C#: Compute the sum of the elements of an given array of integers
Sum of Array Elements
Write a C# Sharp program to compute the sum of the elements of an array of integers.
Visual Presentation:
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 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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics