In this article, we are going to learn how to find the sum of all array elements in C# programming. Here we have an array of size n and we need to sum all n elements of the given array and print the total sum as an output.
Example:
Input: arr[] = {2, 4, 9, 10, 4} Output: 29 Explanation: Sum = 2 + 4 + 9 + 10 + 4 = 29
C# Code to Find Sum of All Array Elements.
// csharp code to find sum of all array elements using System; class Program { static void Main() { // Declare and initialize an array of integers int[] numbers = { 2, 4, 6, 8, 10 }; // Initialize a variable to store the sum int sum = 0; // Iterate through the array and add each element to the sum foreach (int num in numbers) { sum += num; } // Print the result Console.WriteLine("The sum of the array elements is: " + sum); } }
The sum of the array elements is: 30
Working of Above Code:
- We declare an array of integers called numbers and initialize it with some values.
- An integer variable named sum is initialized to zero. This variable will store the sum of the array elements.
- We use a foreach loop to iterate through each element (num) in the numbers array.
- Inside the loop, we add each element's value to the sum variable.
- Finally, we print the sum to the console.
No comments:
Post a Comment