|
|
C# Arrays Tutorial
|
|
Arrays Basic Concepts
|
In C# we have 3 different types of arrays.Just like any other programming language in C# arrays are zero indexed; that is, the array indexes start at zero.
- Single dimensional arrays
- Multidimensional arrays also called as rectangular arrays
- Jagged arrays also called as array-of-arrays
|
|
Declaring,Initializing and Accessing array members from the different types of arrays.
|
Declaring,Initializing and Accessing Single Dimensional Arrays :
|
//Declare a single dimensional string array
string[] Names;
//Initialize the size of the array. This array can hold upto 3 elements of type
string.
Names = new string[3];
//Assing a string "Prasad" to 0th element in Names String
Names[0] = "Prasad";
//Retrieve 0th element from Names array and concatenate CH and assign the resulting
string to 1st element in the Names array
Names[1] = Names[0] + " CH";
//Assign string "Ravindra" to 2nd element in the Names array.
Names[2] = null
//Length property of the array gives the total number of elements present in an
array. In our example Names.Length.ToString() would return 3, as there are 3 elements
present in the array
Names.Length.ToString()
//An alternative way of initializing array elements
Names = {"Prasad","CH","Ravi"}; |
Declaring,Initializing and Accessing Multidimensional Arrays :
|
//Decalre a 2 dimensional array which can hold First and Last names of 3 persons
string[,] Names = new string[3, 2];
//Assing the First and Last Name of the first person
Names[0,0] = "Prasad";
Names[0,1] = "CH";
//Assing the First and Last Name of the second person
Names[1,0] = "Giri";
Names[1,1] = "G";
//Assing the First and Last Name of the third person
Names[2,0] = "Kiran";
Names[2,1] = "K";
Table below shows how first and last names are stored in a 2 dimensional array.
For easy inderstanding I also have marked the coordinates of the array index.
|
Prasad(0,0) |
CH(0,1) |
|
Giri(1,0) |
G(1,1) |
|
Kiran(1,1) |
K(2,1) |
//An alternative way of declaring and initializing array elements at the same time
string[,] Names = new string[3, 2] { {"Prasad","CH"}, {"Giri","G"}, {"Ravi","R"}
}; |
Declaring,Initializing and Accessing Jagged Arrays :
|
Jagged arrays are Arrays-of-Arrays. It is easy to understand Jagged arrays with
an example.I want an outer array of size 2 elements. This outer array's each element
should hold another array of 5 elements each. OddEven array below holds a list of
5 odd elements in the first element of the outer array, where as 2nd element of
the outer array holds 5 even numbers.
int[][] OddEven = new int[2][] { new int[] { 1, 3, 5, 7, 9 }, new int[] { 2, 4,
6, 9, 10 } };
OddEven[0][1] would return 3. |
Lets work with an example to understand C# Arrays. Create a webform with a layout as shown in section 1 below |
|
As you can see in figure1, users will enter a list of names in the multiline textbox
delimited by enter key. When "Process Array" button is clicked, the dropdownlist
has to be populated with names we have in the multiline textbox. To achieve this
we will make use of arrays.
|
|
Enter one name per line and click "Process Array" Button
Section 1 |
In the code behind file write the code in Button1_click and Page_load event handlers
as shown in the Code snippet below.The following are the steps required to retrieve
names from the multiline textbox and populate the dropdownlist:
- string NameString = TextBox1.Text
Retrieve the names entered in TextBox1 into a local string variable NameString.
- char[] Seperator = { '\r' }
Declare a character array and initialize it with '\r'. The escape sequence character '\r' is used to represent "Enter Key" stroke. Tabel1 illustrates list of escape sequence characters in C# and what they represent.When
declaring an array, the square brackets ([]) must come after the type, not the identifier.
Placing the brackets after the identifier is not legal syntax in C#.
- string[] NamesArray = NameString.Split(Seperator);
The Split() method will split the string into an array of names depending on the
seperator character we pass. In our case the seperator character is '\n' which represents
"Enter Key Stroke". The return value of the split method is assigned to the NamesArray
which is a string array.
- foreach (string Name in NamesArray)
{
DropDownList1.Items.Add(Name);
}
Loop thru the string array, retrieve each name and add it to the dropdownlist collection
of items.To loop thru the string array, we are using foreach loop. We will discuss
about loops in our later article.
- protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Items.Clear();
}
On page load we are clearing the items collection of DropDownList1.If you donot
do this on Page_Load, and if you click Button1 more than once, the names will be
repeated. This is bcos ASP.NET maintains previously added names in viewstate and
everytime we click Button1, a new set of names will be added leading to duplication.
This is why we have to clear names in Items collection of DropDownList1 in Page_load()
event handler before we add names in the Button1_Click() event. We can also solve
this problem by setting EnableViewState property of DropDownList1 to false. We will
discuss about viewstate and its implications in our later article.Page_load event
will be fired before Button1_Click event. We will discuss about list of events and
the sequence in which they occur in our later article.
|
protected void Page_Load(object sender, EventArgs e)
{
DropDownList1.Items.Clear();
}
protected void Button1_Click1(object sender, EventArgs e)
{
string NameString = TextBox1.Text;
// Retrieve text from the textbox and
store in a string variable
char[] Seperator = { '\r' };
// Declare a seperator character array and assign "\r" for representing the
enter key
string[] NamesArray = NameString.Split(Seperator); // Use the split
method on the NameString to get a string array which will contain names
foreach (string Name in NamesArray)
// Loop thru the array and bind the names to
the dropdownlist
{
DropDownList1.Items.Add(Name);
}
} |
|
Escape Character |
Represents |
|
\' |
single quote |
|
\" |
double quote |
|
\\ |
backslash
|
|
\0 |
Unicode character 0 |
|
\a |
Alert
|
|
\b |
Backspace |
|
\f |
Form feed |
|
\n |
New line |
|
\r |
Carriage return |
|
\t |
Horizontal tab |
|
\v |
Vertical quote |
Table1 |
|
Other related articles :
|
Njoy Programming
ByPrasad Cherukuri
|
|
|
|
what is fibonacci series?
how to write program and algorithm for this?
|
|
What is Fibonacci Series? Fibonacci Series is a series of numbers that starts with 0 and 1, each new number in the series is simply the sum of the two before it.
An example of Fibonacci Series is shown below.... 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ....
The following program shows how to print a Fibonacci Series. using System; namespace FibonacciSeriesExample { class FibonacciSeries { public static void PrintFibonacciSeries(int Number) { int Previous = -1; int Next = 1; for (int i = 0; i < Number; i++) { int Sum = Next + Previous; Previous = Next; Next = Sum; Console.WriteLine(Next); } }
static void Main() { int Limit; Console.WriteLine("How many numbers in the Fibonacci Series do you wish to print?"); Limit = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\n"); Console.WriteLine("The first " + Limit + " number[s] in the Fibonacci Series are: "); PrintFibonacciSeries(Limit); Console.ReadLine(); } } }
|
|
|
Your Questions/Comments/Feedback:
|
|
If you have some questions that needs an answer you can post them here. If you find this page useful please post your comments and feedback.
|
|
|
|
|