Arrays

Creating Arrays

An array is a type of object that contains values called elements. Every elements of an array must contain same type of values.

Array is like Objects and they are created with new Keyword. Array indexes start at ZERO.

Declarations

Example 1: To Practice this,

Go to Start --> Programs --> Ms Visual Studio 2003 --> New Project --> Visual C# Project --> Console Application.

using System;

class Ms_Array1

{

static void Main(string[] args)

{

int[] num;

num = new int[3];

Console.WriteLine (num[0]);

Console.WriteLine (num[1]);

Console.WriteLine (num[2);

}

}

Example 2:

using System;

class Ms_Array2

{

static void Main(string[] args)

{

int[] num;

num = new int[3];

Console.WriteLine (num[0]);

Console.WriteLine (num[1]);

Console.WriteLine (num[2);

Console.WriteLine (num[3); // Error , Because Indexed Value is 0 to 2.

}

}

Question 1 - What will happen when you compile it and Run it?

using System;

class Msq1_Array

{

static void Main(string[] args)

{

int[] num= new int[3];

Console.WriteLine (num[3]);

}

}

  1. Compilation Error.
  2. Compilation and Output will be 0.
  3. System.IndexOutOfRangeException.
  4. Compilation and Output will be 3.

Question 2 - What will happen when you compile it and run it?

using System;

class Msq1_Array

{

static void Main(string[] args)

{

int num[]= new int[3];

Console.WriteLine (num[2]);

}

}

  1. Compilation and Output will be 0.
  2. Compilation Error.
  3. Compilation and Output will be 2.
  4. Compilation without any output.

Question 3 - What will happen when you compile it and run it?

using System;

class Msq3_Array

{

static void Main(string[] args)

{

int num[]= new int[3];

Console.WriteLine (num[0]);

}

}

  1. Compilation and output will be Zero.
  2. Compilation errors.
  3. Compilation without output.
  4. Compilation but Run Time errors.