Tuesday, July 6, 2010

HANDLING ARRAYS


Creating Arrays
An array is a single data variable that can store multiple pieces of data that are each of the same data type. 
To declare an array, you use the square brackets after the data type when you declare the
variable. The basic format of an array declaration is as shown here:
datatype[] name;
datatype is the type for the information you will store. The square brackets indicate that you are declaring an array, and the name is the name of the array variable. The following definition sets up an array variable called num that can hold integer values:
int[] num;
This declaration creates the variable and prepares it to be capable of holding integer values;
however, it doesn’t actually set aside the area to hold the variables. To do that, you need to do the same thing you do to create other objects, which is to initialize the variable using the new keyword. When you instantiate the array, you must indicate how many values will be stored. One way to indicate this number is to include the number of elements in square brackets when you do the initialization:
num = new int[10];
You also can do this initialization at the same time that you define the variable:
int[] num = new int[10];
As you can see, the format for initializing is as follows:
new datatype[nbr_of_elements]

datatype is the same data type of the array, and nbr_of_elements is a numeric value that indicates the number of items to be stored in the array. In the case of the num variable, you can see that 10 integers values can be stored.
Simple program to implement an array-

using System;
     class Program
    {
       public static void Main()
        {
            int[] num = new int[10];
            Console.WriteLine("Enter the integer numbers");
            for (int i = 0; i < 10; i++)
            {
                num[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine("Numbers you have entered are");
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(num[i]);
            }
        }
    }
Initializing Array Elements

You can initialize the values of the individual array elements at the same time that you declare and initialize the array. You can do this by declaring the values after the array declaration. The values are enclosed in a block and are separated by a comma.

char[] name = new char[6] { 'A', 'd', 'i', 't', 'y', 'a' };

It is interesting to note that if you initialize the values in this manner, you do not have to include the array size in the brackets. The following statement is equivalent to the previousstatement:

char[] name = new char[] { 'A', 'd', 'i', 't', 'y', 'a' };

 or
char[] name = { 'A', 'd', 'i', 't', 'y', 'a' };



 The compiler automatically defines this array as 6 elements because that is the number of items being initialized. The following program creates and initializes a character array.

 using System;
     class Program
    {
       public static void Main()
        {
             char[] name = new char[] {'A','d','i','t','y','a', (char) 0 };

             Console.WriteLine("Display content of name array...");

             int i = 0;
             while (name[i] != 0)
                {
                  Console.Write("{0}", name[i]);
                  i++;
                }
              Console.WriteLine("\nDone.....");
        }
    }
      
   
 Working with Multidimensional Arrays
A multidimensional array is an array of arrays. You can even have an array of arrays of arrays. The number of levels can quickly add up. This starts getting complicated, so I recommend that you don’t store more than three levels (or three dimensions) of arrays.
An array of arrays is often referred to as a two-dimensional array because it can be represented
in two dimensions. To declare a two-dimensional array, you expand on what you do with a regular (or one-dimensional) array:
byte[,] scores = new byte[15,30];
A comma is added to the first part of the declaration, and two numbers separated by a command are used in the second part. This declaration creates a two-dimensional array that has 15 elements, each containing an array of 30 elements. In total, the scores array holds 450 values of the data type byte. To declare a simple multidimensional array that stores a few characters, you enter the following:
char[,] letters = new char[2,3]; // without initializing values

This declaration creates a two-dimensional array called letters, which contains two elements that are each arrays that have three character elements. You can initialize the elements within the letters array at declaration time:
char[,] letters = new char[,] { {‘a’,’b’,’c’},{‘X’,’Y’,’Z’} };
Or, you can initialize each element individually. To access the elements of a multidimensional array, you again use the indexes. The first element of the letters array is letters[0,0]. Remember, the indexes start at offset 0, not 1. letters[0,1] is the second element, which contains the letter ‘b’. The letter ‘X’ is letter[1,0] because it is in the second array (offset 1) and is the first element (offset 0). To initialize the letters array outside the declaration, you could do the following:
letters[0,0] = ‘a’;
letters[0,1] = ‘b’;
letters[0,2] = ‘c’;
letters[1,0] = ‘X’;
letters[1,1] = ‘Y’;
letters[1,2] = ‘Z’;

Creating an Array Containing Different-Size Arrays
In the previous section, an assumption was made that in a two-dimensional array, all the subarrays are the same size. This would make the arrays rectangular. What happens if you want to store arrays that are not the same size? Consider the following:
char[][] myname = new char[3][];
myname[0] = new char[] { ‘A’, ‘d’, ‘i’, ‘t’, ‘y’, ‘a’,};
myname[1] = new char[] { ‘K’, ‘.’ };
myname[2] = new char[] { ‘T’, ‘y’, ‘a’, ‘g’, ‘i’ };
The myname array is an array of arrays. It contains three character arrays that are each a different length. Because they are different lengths, you work with their elements differently from the rectangular arrays that you saw before.
Instead of addressing each element by using index values separated by commas, you instead separate the elements into their own square brackets. For example, the following line of code uses the WriteLine method to print the array elements that would be my initials:
System.Console.WriteLine(“{0}{1}{2}”, myname[0][0], myname[1][0], myname[2][0]);
It would be wrong to address these as myname[0,0], myname[1,0], and myname[2,0]. In fact,
you’ll get an error if you try to access the elements this way.

What happens if you want to declare the myname array without initializing it, as was done previously? You know there are three parts to the name, so the first dimension is 3; however,
what should the second dimension be? Because of the variable sizes, you must make multiple instantiations to set up the full array. First, you declare the outside array that will hold the arrays:
char[][] myname = new char[3][];
This declares the myname variable as an array with three elements, each holding a character
array. After you’ve done this declaration, you must initialize each of the individual arrays that will be stored in myname[].
myname[0] = new char[6]; // first array of six elements
myname[1] = new char[2]; // second array of two elements
myname[2] = new char[5]; // third array of five elements

Using a Jagged Two-Dimensional Array:

using System;

 public class Names
 {
 public static void Main()
 {
 char[][] name = new char[3][];

 name[0] = new char[6] {'A', 'd', 'i', 't', 'y', 'a'};
 name[1] = new char[2] {'K', '.'};
 name[2] = new char[5] {'T', 'y', 'a', 'g', 'i'};

 Console.WriteLine("Display the sizes of the arrays...\n");

 Console.WriteLine("Length of name array {0}", name.Length);

 for( int ctr = 0; ctr < name.Length; ctr++)
 Console.WriteLine("Length of name[{0}] is {1}",ctr, name[ctr].Length);
 //---------------------------------------------------------------------

 Console.WriteLine("\nDisplaying the content of the name array...");

 for( int ctr = 0; ctr < name.Length; ctr++)
 {
 Console.Write("\n"); // new line
 for( int ctr2 = 0; ctr2 < name[ctr].Length; ctr2++ )
 {
 Console.Write("{0}", name[ctr][ctr2]);
 }
 }
 Console.WriteLine("\n...Done displaying");
 }
 }
A multidimensional array that contains subarrays of the same size is referred to as rectangular. A multidimensional array that has variable-size subarrays stored is referred to as “jagged.”

The System.Array Class
In C# every array we create is automatically derived from the System.Array class. This class defines a number of methods and properties that can be used to manipulate arrays more efficiently. The following table lists some of the commonly used methods and their purpose.



Method/Property
Description
Clear()
CopyTo()
GetLength()
GetValue()
Length
SetValue()
Reverse()
Sort()
Sets a Range of Elements to empty values
Copies elements from the source array into the destination array
Gives the number of elements in a given dimension of the array
Gets the value for a given index in the array
Gives the length of an array
Sets the value for a given index in the array
Reverse the contents of one dimensional array
Sorts the elements in one dimensional array


Using GetLength()

        int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        int dim= num.GetLength(0);//GetLength(int dimension)
        Console.WriteLine(dim);//output will be 7
        int[,] num1 = new int[2, 3];
        Console.WriteLine( num1.GetLength(0));//output will be 2
        Console.WriteLine( num1.GetLength(1));//output will be 3
Using GetValue()
        int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        int val = (int)num.GetValue(3);//GetValue(int index)
        Console.WriteLine(val);//output will be 4
Using SetValue()
                int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        num.SetValue(12, 4);//SetValue(object value,int index)
        Console.WriteLine(num[4]);//output will be 12
Using Sort()
        int[] num = new int[] { 4, 2, 6, 3, 5, 1, 9 };
        Array.Sort(num);
       for (int i = 0; i < num.Length; i++)
        {
            Console.Write(num[i]);
        }
Output will be 1234569



Using Reverse()
       int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        Array.Reverse(num);
       for (int i = 0; i < num.Length; i++)
        {
            Console.Write(num[i]);
        }
Output will be 7654321

Using Clear()
        int[] num = new int[] { 1, 2, 3, 4, 5, 6, 7 };
        Array.Clear(num, 0, 3);//Clear(Array array,Int index,int length)
                 for (int i = 0; i < num.Length; i++)
        {
            Console.Write(num[i]);
        }

Output will be 0004567


Friday, June 4, 2010

ARRAYLIST CLASS


ARRAYLIST CLASS
An array list is very similar to an array, except that it has the ability to grow. It is represented by the class System.Collections.ArrayList.
The simplest form of instantiation of an ArrayList is illustrated here:
ArrayList baseballTeams = new ArrayList();
  In order to get at the ArrayList class, user need to make a reference to the System.Collections namespace in your project. User can  instantiate an ArrayList by indicating the initial capacity user want. For example:
ArrayList baseballTeams = new ArrayList(20);
It is also possible to set the capacity of the ArrayList directly after a generic instantiation with the use of the Capacity property as shown in the following example:
ArrayList baseballTeams = new ArrayList();
baseballTeams.Capacity = 20
Once the ArrayList is instantiated, user can then add elements using the Add() method. This console application example uses the Add() method and then displays each of the items that were added:
ArrayList baseballTeams = new ArrayList();
baseballTeams.Add("St. Louis Cardinals");
One thing to note about adding items to the ArrayList is that the ArrayList treats all its elements as object references. That means you can store whatever objects user like in an ArrayList, but when accessing the objects, user will need to cast them back to the appropriate data type, as shown here:
string element1 = (string)baseballTeams[1];
When adding items to the ArrayList, user can also specify the location of the item being added using the Insert() method. This is illustrated in the following example:
baseballTeams.Insert(1, "San Francisco Giants"); // inserts at position 1
User can remove elements at a specific point in the collection with the use of the RemoveAt() method. This is done using the following construction:
baseballTeams.RemoveAt(1); // removes object at position 1

SOME IMPORTANT ARRAYLIST METHODS AND PROPERTIES
Methods/property
Description
Add()
Clear()
Contains()
CopyTo()
Insert()
Remove()
RemoveAt()
RemoveRange()
Sort()
Capacity
Count
Adds an object to a list
Removes all the elements from the list
Determines if an element is in the list
Copies a list to another
Inserts an element into the list
Removes the first occurrence of an element
Removes the element at the specified place
Remove a range of elements
Sorts the element
Gets or sets the number of elements in the list
Gets the number of elements currently in the list

using System;
using System.Text;
using System.Collections;

   class Program
    {
        static void Main(string[] args)
        {   //Creating an ArrayList
            ArrayList names = new ArrayList();
            //Adding the elements to the ArrayList
            Console.WriteLine("Using Add().......");
            names.Add("Aditya Tyagi");//Add(Object obj)
            names.Add("Dev Pratap");
            names.Add("Arun Kumar");
            names.Add("Arun Solanki");
            names.Add("Deepak");
            names.Add("Rajesh");
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }
            //Using Remove()
            Console.WriteLine("Using Remove()........");
            names.Remove("Rajesh");Remove(object obj)
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }
            //Using RemoveAt()
            Console.WriteLine("Using RemoveAt().......");
            names.RemoveAt(4);//RemoveAt(int index)
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }
            //Using Insert()
            Console.WriteLine("Using Insert().......");
            names.Insert(4, "Deepak");//Insert(int index,object obj)
            names.Insert(5, "Rajesh");
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }
            //Using RemoveRange()
            Console.WriteLine("Using RemoveRange().......");
            names.RemoveRange(4, 2);//RemoveRange(int index,int count)
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }

            //Using Sort()
            Console.WriteLine("Using Sort().......");
            names.Sort();
            for (int i = 0; i < names.Count; i++)
            {
                Console.WriteLine(names[i]);
            }

            //Using Contains()
            Console.WriteLine("Using Contains().......");
            bool b= names.Contains("Aditya Tyagi");//Contains(object obj)
            Console.WriteLine(b);

            //Using Clear()
            Console.WriteLine("Using Clear().......");
            names.Clear();
            Console.WriteLine(names.Count);
           
            




        }
    }

Output:
Using Add().......
Aditya Tyagi
Dev Pratap
Arun Kumar
Arun Solanki
Deepak
Rajesh
Using Remove()........
Aditya Tyagi
Dev Pratap
Arun Kumar
Arun Solanki
Deepak
Using RemoveAt().......
Aditya Tyagi
Dev Pratap
Arun Kumar
Arun Solanki
Using Insert().......
Aditya Tyagi
Dev Pratap
Arun Kumar
Arun Solanki
Deepak
Rajesh
Using RemoveRange().......
Aditya Tyagi
Dev Pratap
Arun Kumar
Arun Solanki
Using Sort().......
Aditya Tyagi
Arun Kumar
Arun Solanki
Dev Pratap
Using Contains().......
True
Using Clear().......
0
Press any key to continue . . .


Friday, May 14, 2010

The StringBuilder Class



The StringBuilder class is provided in the System.Text namespace to create an object that can hold a string value that can be changed. An object created with the StringBuilder class operates similarly to a string. The difference is that methods of a StringBuilder can directly manipulate the value stored. The methods and properties for a StringBuilder object are listed in table given below.
Table :The StringBuilder Methods and Properties
Methods or Properties                        Description
Append:                                 Appends an object to the end of the current StringBuilder.
AppendFormat:                    Inserts objects into a string base on formatting specifiers.
Capacity:                                Sets or gets the number of characters that can be held. Capacity can be increased up to the value of MaxCapacity.
Chars:                                     Sets or gets the character at a given index position using indexer notation.
EnsureCapacity:                    Ensures that the capacity of StringBuilder is at least as big as a provided
Value:                                     If the value is passed to EnsureCapacity, the value of the Capacity property is set to this new value. If MaxCapacity is less than the value passed, an exception is thrown.
Equals:                                   Determines whether the current StringBuilder is equal to the value passed.
Insert:                                    Places an object into StringBuilder at a given location.
Length:                                   Sets or gets the length of the current value stored in StringBuilder. Length cannot be larger than the Capacity of StringBuilder. If the current value is shorter than Length, the value is truncated.
MaxCapacity:                        Gets the maximum capacity for StringBuilder.
Remove:                                 Removes a specified number of characters, starting at a specified location within the current StringBuilder object.
Replace:                                 Changes all copies of a given character with a new character.
ToString:                               Converts StringBuilder to String.


The StringBuilder class can be used like other classes. The following program uses the StringBuilder object and several of the methods and properties presented in above table. This program has a user enter first, last, and middle names. The values are combined into a StringBuilder object.

The StringBuilder class is used to represent mutable strings. It starts at a predefined size (16 characters by default) and grows dynamically as more string data is added. It can either grow unbounded or up to a configurable maximum. For example:
=== Program that uses Replace () and Append () ===
using System;
using System.Text;

class Program
{
    static void Main()
    {
        StringBuilder builder = new StringBuilder("This is an example string");
        builder.Replace("an", "the"); // Replaces 'an' with 'the'.
        Console.WriteLine(builder);
        builder.Append(" that is an example.");
        Console.WriteLine(builder);
        
    }
}

=== Output of the program ===
This is the example string
This is the example string that is an example

=== Program that uses AppendFormat () ===
using System;
using System.Text;

class Program
{
    static int[] sb = new int[]{1,4,6};
   
    static void Main()
    {
        StringBuilder b = new StringBuilder();
        foreach (int i in sb)
        {
            b.AppendFormat("int: {0:0.0}\n",i);
        }
        Console.WriteLine(b.ToString());
    }
}
 

=== Output of the program ===

int: 1.0
int: 4.0
int: 6.0


=== using Remove () ===

 StringBuilder st = new StringBuilder("Football");
 st.Remove(4, 4);//Remove(int StartIndex,int length).
 Console.WriteLine(st);//Foot

=== using Insert () ===

StringBuilder st = new StringBuilder("Foot");
st.Insert(4, "ball");
Console.WriteLine(st);//Football

=== using Equals () ===
StringBuilder sb = new StringBuilder("c#");
StringBuilder sb1 = new StringBuilder("c#");
bool b= sb.Equals(sb1);
Console.WriteLine(b);//True

The chief advantage of a StringBuilder object over a string object is that it preallocates a default initial amount of memory in an internal buffer in which a string value can expand and contract. When that memory is used, however, .NET must allocate new memory for this internal buffer. You can reduce the frequency with which this occurs by explicitly defining the size of the new memory using either of two techniques. The first approach is to set this value when the StringBuilder class constructor is called. For example, the code:
        StringBuilder sb = new StringBuilder(200);

specifies that a StringBuilder object can hold 200 characters before new memory must be allocated.
The second approach is to change the value after the StringBuilder object has been created, using one of the following properties or methods of the StringBuilder object:
        sb.Capacity = 200;
        sb.EnsureCapacity(200);