All programming languages come across the concept of arrays. So this is very important. Basically arrays are used to store a group of data which are having same data type. I will few examples of arrays in this post.
class abc
{
static void Main()
{
int[] array;
array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
Console.WriteLine(array[0]);
array[0]++;
Console.WriteLine(array[0]);
++array[1];
Console.WriteLine(array[1]);
int i=1;
Console.WriteLine(array[i]);
i = 5;
Console.WriteLine(array[i]); //Error
Console.ReadKey();
}
Error:
Index was outside the bounds of the array.
We declare arrays with a set of [] brackets. As our example int[] array means array is like of int[]. And instantiate array with new keyword. Number 3 in the square bracket indicate that the user want to store 3 items or 3 records. Hence in the array the items count/index start at ‘0’ and end at ‘n-1’. As shown in the example it starts at ‘0’ and end at ‘2’. But we are trying to pull the record that is not created so we got this error.
static void Main()
{
int[] array;
array = new int[3];
array[0] = 1;
array[1] = 2;
array[2] = 3;
Console.WriteLine(array[0]);
array[0]++;
Console.WriteLine(array[0]);
++array[1];
Console.WriteLine(array[1]);
int i=1;
Console.WriteLine(array[i]);
i = 2;
Console.WriteLine(array[i]); //Error
Console.ReadKey();
}
OutPut
1
2
3
3
3
Hurry! No errors, It looks we are having more code with similar content lets use loop concept to minimize the code. As shown below
class abc
{
static void Main()
{
int[] array;
array = new int[3];
int i;
for (i = 0; i < 3; i++)
array[i] = i + 1;
for (i = 0; i < 3; i++)
Console.WriteLine(array[i]);
Console.ReadKey();
}
}
OutPut
1
2
3
Hence we minimized the code and removed all errors. Now we will see how ‘foreach’ works with same code. As shown below.
class abc
{
static void Main()
{
int[] array;
array = new int[3];
int i;
for (i = 0; i < 3; i++)
array[i] = i + 1;
foreach(int p in array)
Console.WriteLine(p);
Console.ReadKey();
}
}
OuPut
1
2
3
ya its correct
ReplyDelete