C#: Find the sum of all elements of array
Write a program in C# Sharp to find the sum of all array elements.

Sample Solution:-
C# Sharp Code:
using System;  // Importing necessary namespace
public class Exercise3  // Declaration of the Exercise3 class
{  
    public static void Main()  // Main method, entry point of the program
    {
        int[] a = new int[100];  // Declaration of an integer array 'a' with size 100
        int i, n, sum = 0;  // Declaration of variables 'i', 'n', and 'sum' and initializing 'sum' as 0
		
        // Display a message about finding the sum of all elements of an array
        Console.Write("\n\nFind sum of all elements of array:\n");
        Console.Write("--------------------------------------\n");
        // Prompt the user to input the number of elements to be stored in the array
        Console.Write("Input the number of elements to be stored in the array: ");
        n = Convert.ToInt32(Console.ReadLine());  // Read the number of elements from the user and store it in 'n'
        Console.Write("Input {0} elements in the array:\n", n);  // Prompt the user to input 'n' elements
        // Loop to read 'n' elements from the user and store them in the array 'a'
        for (i = 0; i < n; i++)
        {
            Console.Write("element - {0} : ", i);  // Prompt for input element number
            a[i] = Convert.ToInt32(Console.ReadLine());  // Read user input and store it in the array 'a'
        }
        // Loop to calculate the sum of all elements stored in the array 'a'
        for (i = 0; i < n; i++)
        {
            sum += a[i];  // Calculate the sum by adding each element of the array 'a' to 'sum'
        }
        // Display the sum of all elements stored in the array 'a'
        Console.Write("Sum of all elements stored in the array is : {0}\n\n", sum);
    }
}
Sample Output:
Find sum of all elements of array: -------------------------------------- Input the number of elements to be stored in the array :4 Input 4 elements in the array : element - 0 : 2 element - 1 : 4 element - 2 : 6 element - 3 : 4 Sum of all elements stored in the array is : 16
Flowchart:

Go to:
PREV : Write a program in C# Sharp to read  n number of values in an array and display it in reverse order.
NEXT : Write a program in C# Sharp to copy the elements one array into another array.
C# Sharp Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
