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);
         
            Console.ReadLine();
        }
    }
}

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.

arraytotal

PHP & OOP: A simple class declaration

This entry is part 3 of 11 in the series PHP & OOP

We first look at this simple class declaration.

<?php
class SimpleClass
{
    // property declaration
    public $var = 'a default value';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

$simple_object = new SimpleClass();
echo $simple_object->displayVar();

?>

In object-oriented terminology, a property is actually the variable of a class and a method is a function declared inside the class.

In the above example, we have used the method displayVar() to access the variable $var.  The variable $var is a property of the class SimpleClass.

Visibility

The visibility or scope of a property or method can be defined by prefixing the declaration with the keywords public, protected or private.

Class members declared public can be accessed everywhere.

Members declared protected can be accessed only within the class itself and by inherited and parent classes.

Members declared as private may only be accessed by the class that defines the member.