Array Concept
class zzz{
public static void Main()
{
int[] a;
a= new int[3];
a[0]= 1; a[1]= 10; a[2]= 20;
System.Console.WriteLine(a[0]);
a[0]++;
System.Console.WriteLine(a[0]);
int i;
i=1;
System.Console.WriteLine(a[i]);
i=2;
System.Console.WriteLine(a[i]);
}
}
Output
1
2
10
20
//
Here 'a' is an array of ints. You declare arrays with a set of [] brackets. At this point it is not known how large the array will be. For that we have a=new int[3]; after new we have int meaning we want to create a variable of type int. We are putting 3 in the square brackets meaning we want to store 3 ints. This will create three ints a[0], a[1] and a[2]. They are then initialized to the values 1,10 and 20 respectively. To initialize an array variable we use the name, i.e. in this case a and follow it with the open and close [] brackets. Inside them we put the array number. The first variable is called a[0] , the second a[1] and so on. C# like most computer programming languages likes to start counting from 0 and not 1. Therefore, the last variable is a[2] and not a[3].
Since an array is many of the same type, they all have the same name. In our earlier example, even if we have many books, all the books will be called books. However, to refer to them individually you can say book1, book2, book3 etc.
WriteLine will display the value stored in a[0] which is 1. a[0]++ will increment the value stored in a[0] by one. WriteLine will now display 2.
Thereafter, the variable i is declared as an int. It is then initialized to 1. Within the WriteLine function we have a[i]. It is not specifically stated which variable, instead we have said a[i]. There is no variable called a[i], but i has a value 1, so it is read as a[1]. Hence the value stored at a[1], which is 10, is displayed. The next WriteLine will display the value stored in a[2] as i is reinitialized to 2.
Doing this makes our program more generic. We haven't specifically stated which variable, we are letting a variable called i decide the name of the variable.
//
Array in reverse order
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//int j;
int[] nums1 = new int[10];
int[] nums2 = new int[10];
for (int i = 0; i < nums1.Length; i++)
{
nums1[i] = i;
}
//display
Console.WriteLine("display");
Console.WriteLine(".................");
for (int i = 0; i < nums1.Length; i++)
{
Console.Write(nums1[i] + " ");
}
Console.WriteLine();
//lets reverse
if (nums2.Length >= nums1.Length)
{
int i,k;
for ( i = 0, k=(nums1.Length-1); i < nums1.Length; i++,k--)
{
nums2[k]=nums1[i];
}
}
Console.WriteLine("reversed contents");
for(int i=0;i<nums2.Length;i++)
{
Console.WriteLine(nums2[i]);
}
Console.ReadLine();
}
}
}
/* both nums1 and nums2 changes ...
display
0 1 2 3 4 5 6 7 8 9
reversed contents
9
* 8
* 7
* 6
* 5
* 4
* 3
* 2
* 1
* 0
*
*/
No comments:
Post a Comment