Thursday, 13 November 2014

Arrays


What is an array?
Before I explain what an array is, let us consider the program below;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace array
{
    class Program
    {
        static void Main(string[] args)
        {
            double d1,d2,d3,d4,d5,d6,d7,d8,d9,d10,sum,average;
            d1 = 2;
            d2 = 3.5;
            d3 = 5;
            d4 = 3.6;
            d5 = 6;
            d6 = 4;
            d7 = 7.2;
            d8 = 9;
            d9 = 8;
            d10 = 13;
            sum = d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + d9 + d10;
            average = sum / 10;
            Console.WriteLine("Sum= " + sum);
            Console.WriteLine("Average=" + average);
        }
    }
}

From the program above, let us assume that the variable d is up to 100. Writing the code to add up the values will take the you, the programmer a lot of time. In a situation like this, you have to know how to make use of array.
An array is an organized collection of anything (numbers, name of persons, places, etc). An array can also be defined as a group of numbers. Let us assume you want to create a program that would use a series of numbers, you start by declaring each variables one after the other. Instead of using individual variables that constitute same characteristics, you can group them in an entity like a regular variable.
The disadvantage of array in C-sharp(C#) or any other object oriented programming (OOP) is that once an array has been created it cannot be made larger or smaller to accommodate more or fewer values.
The syntax of an array is:
Type [ ] arrayname
where type is the data type, [ ] indicates an array, arrayname is name given to the array.
e.g
double [ ] myarray;
int [ ] school;
Let us now re-write the program above in array form
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace array
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] myprogram;
            myprogram=new double[10]{2.0,3.5,5.0,3.6,6.0,4.0,7.2,9.0,8.0,13.0};
            double sum=0;
            for(int i=0; i<10; i++)
            {
                sum=sum+myprogram[i];
            }
            double average=sum/10;
            Console.WriteLine("Sum= "+sum);
            Console.WriteLine("Average="+average);
        }
    }
}

The two programs above give the result when run.

No comments :

Post a Comment