Latest Post

Tuesday, 3 January 2017

How to find the sum of Array elements [C#]

Write a program in C# that simply takes elements of the array from the user and finds the sum of these elements.

Following is the simple C# code :
class Lab
    {
        static void Main(string[] args)
        {
            int SIZE = 1000;
            int[] myArray = new int[SIZE];
            int i, number, sum = 0;

            Console.Write("Enter size of the array: ");
            number = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter {0} elements in the array: ", number);
            for (i = 0; i < number; i++)
            {
                myArray[i] = Convert.ToInt16(Console.ReadLine());
            }

            for (i = 0; i < number; i++)
            {
                sum = sum + myArray[i];
            }
            Console.Write("Sum of the Array is = " + sum);
            Console.ReadLine();
        }
    }

Output:-
Enter size of the array: 10
Enter 10 elements in the array: 45
78
12
3
65
89
15
25
66
82
Sum of the Array is = 480


Government Jobs