Friday, 17 August 2018

C#: Arrays

An array is a series of elements of the same type placed in contiguous memory locations. Elements in the array are accessed using index positions.

Syntax
datatype[] arrayName = new datatype[sizeOfTheArray];

Ex:
int[] evenNumbers = new int[10];

Suppose if you want to calculate sum of 9 integers, you have to define 9 variables like below

    int var1, var2, var3, var4, var5, var6, var7, var8, var9;

    var1 = 5;
    var2 = -10;
    var3 = 7;
    var4 = 8
    var5 = 11;
    var6 = 12;
    var7 = 14;
    var8 = 21;
    var9 = 0;

By using arrays we can declare like below

    int var[] = new int[9];

    var[0] = 5;
    var[1] = -10;
    var[2] = 7;
    var[3] = 8
    var[4] = 11;
    var[5] = 12;
    var[6] = 14;
    var[7] = 21;
    var[8] = 0;

As you see, Array indexes starts from 0. var[0] represents 5, var[2] represents 7 and so on.

Program.cs
using System;

class Program
{
    static void Main(string[] args)
    {
        int[] var = new int[9];

        var[0] = 5;
        var[1] = -10;
        var[2] = 7;
        var[3] = 8;
        var[4] = 11;
        var[5] = 12;
        var[6] = 14;
        var[7] = 21;
        var[8] = 0;

        Console.WriteLine("var[0] = {0}", var[0]);
        Console.WriteLine("var[1] = {0}", var[1]);
        Console.WriteLine("var[2] = {0}", var[2]);
        Console.WriteLine("var[3] = {0}", var[3]);
        Console.WriteLine("var[4] = {0}", var[4]);
        Console.WriteLine("var[5] = {0}", var[5]);
        Console.WriteLine("var[6] = {0}", var[6]);
        Console.WriteLine("var[7] = {0}", var[7]);
        Console.WriteLine("var[8] = {0}", var[8]);
    }
}

Output
var[0] = 5
var[1] = -10
var[2] = 7
var[3] = 8
var[4] = 11
var[5] = 12
var[6] = 14
var[7] = 21
var[8] = 0




Previous                                                 Next                                                 Home

No comments:

Post a Comment