C Sharp/Arrays

From Meshplex

Jump to: navigation, search
Image:Csharp_programming.gif

Main Home

Basics
C# Tutorial Home
C# - Introduction to Visual Studio IDE
Introduction to C#
C# - Overview
C# - Statements
C# - Data Types
C# - Variables
C# - Operators
C# - Flow Control
C# - Variables II

C# - Functions and Methods
C# - Classes and Objects I
C# - Enumerations
C# - Dates and Times
C# - Random Numbers

Advanced
C# - Inheritance
C# - Polymorphism
C# - Garbage Collection
C# - Operator Overloading
C# - Encapsulation
C# - Properties
C# - Indexers
C# - Exceptions
C# - GUI
C# - Delegates
C# - Events
C# - Components
C# - Multithreading
C# - Regular Expressions
C# - Graphics and Multimedia
C# - Files and Streams
C# - XML
C# - Database, SQL and ADO.NET
C# - ASP.NET Web Forms and Web Controls
C# - Web Services
C# - Network Programming
C# - Datastructures and Collections
C# - Enumerations and Iterators
C# - .NET Assemblies
C# - CLR
C# - Visual Studio Debugger
C# - Namespaces
C# - Generics
C# - MS Intermediate Language
C# - Deploying Windows Application

Contents

[edit] Csharp Arrays

Arrays allow you to store many values into one variable of the same type. It is not efficient to declare a separate variable for each value. It would be a very gruelling task to declare two thousand variables by hand. This is where the array comes into play.


Lets print a list of our family members. Here is the code.

using System;
 
class Program
{
    static void Main(string[] args)
    {
        string f1 = "Mike";
        string f2 = "Jerry";
        string f3 = "Shina";
        string f4 = "Hellen";
        string f5 = "John";
        string f6 = "Luther";
        string f7 = "Ben";
        string f8 = "Cleo";
        string f9 = "Jose";
        string f10 = "Maria";
 
        Console.WriteLine(f1);
        Console.WriteLine(f2);
        Console.WriteLine(f3);
        Console.WriteLine(f4);
        Console.WriteLine(f5);
        Console.WriteLine(f6);
        Console.WriteLine(f7);
        Console.WriteLine(f8);
        Console.WriteLine(f9);
        Console.WriteLine(f10);
        Console.Read();
    }
}

Output:

Mike
Jerry
Shina
Helen
John
Luther
Ben
Cleo
Jose
Maria

Can you imagine how much we had to type if we had a thousand members? That is alot of typing and is very inconvenient. We can use arrays to make this job alot simpler.


Declare an array:

string[] x = {"I", "am", "learning", "C#");
  • Index 0: I
  • Index 1: am
  • Index 2: learning
  • Index 3: C#

Note: C# is not in position 4 it is in position 3. Many people confuse the array positions because C# uses index 0 instead of index 1 for the beginning of the index.


Arrays can also be declared in these fashions too:

string[] MyFamily = new string[10];
string[] MyFamily = new string[arraysize];   //Beware arraysize MUST be a const
string[] MyFamily = new string[3] {"Billy", "Kate", "Devan"};


Example:

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string[] MyFamily = {"Mike", //Index 0
  8. "Jerry", //Index 1
  9. "Shina", //Index 2
  10. "Helen", //Index 3
  11. "John", //Index 4
  12. "Luther", //Index 5
  13. "Ben", //Index 6
  14. "Cleo", //Index 7
  15. "Jose", //Index 8
  16. "Maria"}; //Index 9
  17.  
  18. for (int x = 0; x <= 9; ++x) //Iterate from 0 to 9
  19. Console.WriteLine(MyFamily[x]);
  20.  
  21. Console.Read();
  22. }
  23. }

Output:

Mike
Jerry
Shina
Helen
John
Luther
Ben
Cleo
Jose
Maria

Line 7: This is also acceptable

string[] MyFamily = new string[10] {"Mike",


Line 18: Access an element of an array:

MyFamily[index]

[edit] foreach Loops

Before we continue to multidimensional arrays I wanted to cover foreach loops first. foreach loops is a luxury to programmers and can prevent bugs in your program. There is a slight cost to using this luxury. Using foreach loops can have a slight performance hit but not anything noticable.

With foreach loops you don't need to know the size of the array because the foreach loop iterates through each element in the array and it knows when to stop. With for loops you must know the size of the array and tell it when to stop. This is unnecessary in a foreach loop.


Syntax:

foreach (<Type> name in <array>)
{
     //code here
}


Example:

using System;
 
class Program
{
    static void Main(string[] args)
    {
        string[] MyFamily = {"Mike",    //Index 0
                            "Jerry",    //Index 1
                            "Shina",    //Index 2
                            "Helen",    //Index 3
                            "John",     //Index 4
                            "Luther",   //Index 5
                            "Ben",      //Index 6
                            "Cleo",     //Index 7
                            "Jose",     //Index 8
                            "Maria"};   //Index 9
 
        foreach(string FamilyTemp in MyFamily)    //Iterate from 0 to 9
            Console.WriteLine(FamilyTemp);
 
        Console.Read();
    }
}

Output:

Mike
Jerry
Shina
Helen
John
Luther
Ben
Cleo
Jose
Maria

FamilyTemp is a temporary variable that holds the contents of the actual array. This provides a buffer so you can't modify or change the values MyFamily. When using a foreach loop MyFamily becomes read-only so you can't change it.

[edit] Getting Array Size

Knowing the size of your array is important in looping through each element in an array. The loop must know when to stop. The demonstration below gives an example of how to get the size or obtain the amount of elements in an array.

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. int[] x = { 1, 45, 155, 78, 12 };
  8.  
  9. for(int a = 0; a <= (x.Length-1); a++)
  10. Console.WriteLine(x[a]);
  11.  
  12. Console.WriteLine("Array has " + x.Length + " elements");
  13. Console.Read();
  14. }
  15. }

Output

1
45
155
78
12
Array has 5 elements


Take a look at Line 9. Why could'nt (x.Length) work instead. I will explain below. The array has 5 elements right? But remember the index starts at 0.

Index 0: 1
Index 1: 45
index 2: 155
index 3: 78
index 4: 12

Now remember (x.Length) = 5 but the index ends at 4. There are five index values but the index starts at 0 not one. This is a classic case of the off by one error.

/comment for the previous paragraph / well in line 9 [ a<=(x.Length-1) ; ] be replaced by [ a < x.Length ; ] it will work just a suggestion :)

[edit] C# Multidimensional Arrays

Multidimensional arrays are arrays within arrays also known as rectangular arrays. It may become necessary to nest an array in an array. For example, suppose that you have a list of families and you want to group each family in an array. That means you will have an array of families and an array of family members. Lets take a look at some code.


Syntax:

<Type>[,] ArrayName;

Arrays can be as many dimensions as you wish. The synatx for this is:

<Type>[,,,,,] <ArrayName>


Declare an array: Example 1:

string [,] Families = new string [2,3];


Note: Multidimensional arrays are rectangular, that means the array must have the same amount of elements in each row. For example, each family must have the same amount of family members. We all know that this is statistically not possible. So to solve this problem you will need to identify a value that defines an empty space. That means if you have two families: The first family has 5 members and the second family has only 2 members


Family 1: Jamal, Jane, Mitch, Anthony, Corel

Family 2: Don, Joan

string[,] Families = new string [2,5] {{"Jamal", "Jane", "Mitch", "Anthony", "Corel"},  //Family 1
                                       {"Don", "Joan", "xxx", "xxx", "xxx"}};           //family 2
[2,5]  //2 rows and 5 elements in each row

Important: Each row MUST have the same amount of elements thats why we had to use filler characters xxx.


Code:

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string[,] Families = new string[2, 5] {{"Jamal", "Jane", "Mitch", "Anthony", "Corel"},
  8. {"Don", "Joan", "xxx", "xxx", "xxx"}};
  9.  
  10. for (int x = 0; x < 2; ++x) //Iterate through each row
  11. {
  12. Console.WriteLine("Family" + (x + 1) + ":");
  13. for (int y = 0; y < 5; ++y) //Iterate through each element in row
  14. {
  15. if(Families[x, y] != "xxx") //if array value does not equal "xxx" then print
  16. Console.WriteLine(Families[x, y]);
  17. }
  18. Console.WriteLine(""); //Print a blank space between rows
  19. }
  20.  
  21. Console.Read();
  22. }
  23. }
Family 1:
Jamal
Jane
Mitch
Anthony
Corel

Family 2:
Don
Joan
  • Line 7: Represents row 1
  • Line 8: Represents row 2
  • Line 10: This is outer loop which iterates through each row
  • Line 12: Prints Family (x+1) and then :
  • Line 13: This is inner loop which iterates through each element in row

[edit] C# Jagged Arrays

Jagged arrays are my favorite. They are more flexible than the rectangular arrays. With Jagged arrays the rows don't have to be the same size. So that means you don't need an if statement to test for filler characters.


Declare Jagged Array

string[][] Families = new string [2][5];

Initialize Jagged Array

 string[][] Families = new string[2][5] {{"Jamal", "Jane", "Mitch", "Anthony", "Corel"},
                                        {"Don", "Joan"}};   //Hooray no fillers


for loop example

  1. using System;
  2.  
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string[][] Families = {new string[] {"Jamal", "Jane", "Mitch", "Anthony", "Corel"}, //array 0
  8. new string[] {"Don", "Joan"}}; //array 1
  9.  
  10. for (int x = 0; x < Families.GetLength(0); ++x) //GetLength get the size of first array
  11. {
  12. Console.WriteLine("Family" + (x + 1) + ":");
  13. for (int y = 0; y < Families[x].GetLength(0); ++y)
  14. {
  15. Console.WriteLine(Families[x][y]); //No if statement
  16. }
  17. Console.WriteLine("");
  18. }
  19.  
  20. Console.Read();
  21. }
  22. }
Family 1:
Jamal
Jane
Mitch
Anthony
Corel

Family 2:
Don
Joan

Look at line 13. Families.GetLength(0) fetches the first dimension of the array that you want the length of. Families.GetLength(1) will get the second dimension.


foreach Loop example

using System;
 
class Program
{
    static void Main(string[] args)
    {
        string[][] Families = {new string[] {"Jamal", "Jane", "Mitch", "Anthony", "Corel"}, 
                               new string[] {"Don", "Joan"}};
 
        int x = 0;   //Keep track of families
        foreach (string[] TempArray in Families)      //Iterate through top array
        {
            ++x;
            Console.WriteLine("Family" + x + ":");
            foreach (string Element in TempArray)     //Iterate through sub array
            {
                Console.WriteLine(Element);
            }
            Console.WriteLine("");
        }
 
        Console.Read();
    }
}
Family 1:
Jamal
Jane
Mitch
Anthony
Corel

Family 2:
Don
Joan
Personal tools
Interesting Sites
ListSergeant