C#: Using for loop to find array total

This entry is part 36 of 71 in the series C#

In this example, we demonstrate on using a for loop to find the total sum of an array.

We have talked about property.  Here, we used an array property Length to find the number of element in the array.  This is shown in line 13 where we access the length of the array using array.Length.

This number is needed for the for loop to calculate the total.

using System;

namespace MyArray
    class Program
        static void Main()

            double[] array = { 2.5, 3.2, 5.21, 6.0 };

            double sum = 0;
            int length = array.Length;  //finding the length using array propertye Length

            for (int i = 0; i < length; i++ )
                sum = sum + array[i];

            double average = sum / length;

            Console.WriteLine("Sum: {0}", sum);
            Console.WriteLine("Average: {0}", average);

The program begins by initializing a variable sum to 0. Then it loops through the values stored in array, adding each one to sum.

By the end of the loop, sum has accumulated the sum of all values in the array.

The resulting sum is divided by the number of elements to calculate the average.


Series Navigation<< C#: Declaring an array
C#: Using foreach to print out array elements >>