Array in C#
Let assume that we have to calculate the area of 5 rectangles. We can declare 5 variables each for length and width and then another 5 variables for the area as follows.
int length1,length2,length3,length4,length5; int breadth1,breadth2, breadth3,breadth4, breadth5; int area1,area2, area3, area4,area5 ; |
While this is pefectly correct way to define the variables in this way, C# provides the concept of array.Here is how you do the same thing using arrays.
int[] length; int[] breadth; int[] area; |
The statement int[] length says that length is an array of type int. C# is different from other languages in that [] comes after the type instead of the identifier.
Let us now go ahead an write a program that will print the areas of 5 rectangles.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArrayExample { class Program { static void Main(string[] args) { int[] length; int[] breadth; int[] area; length = new int[5]; breadth = new int[5]; area = new int[5]; int i; length[0] = 10; length[1] = 20; length[2] = 30; length[3] = 40; length[4] = 50; breadth[0] = 5; breadth[1] = 15; breadth[2] = 25; breadth[3] = 35; breadth[4] = 45; for (i = 0; i <= 4; i++) { area[i] = length[i] * breadth[i]; Console.Write("Area = "); Console.WriteLine(area[i]); } Console.ReadLine(); } } } |
If we execute this example we get the following output
Area = 50 Area = 300 Area = 750 Area = 1400 Area = 2250 |
Arrays help organize the codes. The statements
length = new int[5]; breadth = new int[5]; area = new int[5]; |
create instance of the array types. Now instead of length1, length2, length3, length4 and length5 we have length[0],length[1],length[2],length[3],length[4]. Note that the array index starts from 0 and not 1.
In the next post we will take a look at some simple GUI "Hello World" proram.