Programming References and tutorials for Developers.

C# Looping Statement

By The Saint on Saturday, March 07, 2009

comments (0)

Filed Under:

C# just like Java and C++ it also provides looping statements.
Common looping statements:

for loop
while
do while

Three components of a looping statement:
1. Initial value
2. Condition
3. Change of state

while loop
A while loop executes a statement, or a block of statements wrapped in curly braces, repeatedly until the condition specified by the Boolean expression reach the false condition.

The boolean expression is evaluated before any code in the following block has executed. When the boolean expression evaluates to true, the statements will execute. Once the statements have executed, control returns to the beginning of the while loop to check the boolean expression again.

Syntax in creating a while (expression) loop.

while(expression)
Statements...
}

Example:

int counter=0; //initial value

while(counter<5) style="font-weight: bold;">do while Loop
A do while loop is just like a while loop, except that it checks its condition at the end of the loop. This means that the do loop is guaranteed to execute at least one time. On the other hand, a while loop evaluates its Boolean expression at the beginning and there is generally no guarantee that the statements inside the loop will be executed, unless you program the code to explicitly do so.

Syntax in creating a do while (expression) loop.

do{
Statement...
}while(expression)

Example:

int counter=0;

do{
Console.WriteLine(counter);
counter++;
}while(counter<5);

Program Output:
0
1
2
3
4

The for Loop

A for loop works like a while loop, except that the syntax of the for loop includes initialization and condition modification. for loops are appropriate when you know exactly how many times you want to perform the statements within the loop. The contents within the for loop parentheses hold three sections separated by semicolons (; ; ) { }.

The initializer list is a comma separated list of expressions. These expressions are evaluated only once during the lifetime of the for loop. This is a one-time operation, before loop execution. This section is commonly used to initialize an integer to be used as a counter.

Once the initializer list has been evaluated, the for loop gives control to its second section, the boolean expression. There is only one boolean expression, but it can be as complicated as you like as long as the result evaluates to true or false. The boolean expression is commonly used to verify the status of a counter variable.

When the boolean expression evaluates to true, the statements within the curly braces of the for loop are executed. After executing for loop statements, control moves to the top of loop and executes the iterator list, which is normally used to increment or decrement a counter. The iterator list can contain a comma separated list of statements, but is generally only one statement.

for(int counter = 0; counter<5; counter++)
{
Console.WriteLine(counter);
}

Program Output:
0
1
2
3
4

c# ArrayList Class

By The Saint on Thursday, January 29, 2009

comments (2)

Filed Under:

c# ArrayList Class
Static arrays are not very useful when the size of an array is unknown in advance or is likely to change during the lifetime of a program. One solution to this problem is to use a type of array that automatically resizes itself when the array is out of storage space. This array is called an ArrayList and it is part of the System.Collections namespace in the .NET Framework library.

An ArrayList object has a Capacity property that stores its size. The initial value of the property is 16. When the number of elements in an ArrayList reaches this limit, the Capacity property adds another 16 elements to the storage space of the ArrayList. Using an ArrayList in a situation where the number of elements in an array can grow larger, or smaller, can be more efficient than using ReDim Preserver with a standard array.

Members of the ArrayList Class
The ArrayList class includes several methods and properties for working with ArrayLists. Here is a list of some of the most commonly used methods and properties:

- Add(): Adds an element to the ArrayList.
- AddRange(): Adds the elements of a collection to the end of the ArrayList.
- Capacity: Stores the number of elements the ArrayList can hold.
- Clear(): Removes all elements from the ArrayList.
- Contains(): Determines if a specified item is in the ArrayList.
- CopyTo(): Copies the ArrayList or a segment of it to an array.
- Count: Returns the number of elements currently in the ArrayList.
- GetRange(): Returns a subset of the ArrayList as an ArrayList.
- IndexOf(): Returns the index of the first occurrence of the specified item.
- Insert(): Insert an element into the ArrayList at a specified index.
- InsertRange(): Inserts the elements of a collection into the ArrayList starting at the specified
index.

Example:


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace ArraysBlogs
{
class Program
{
static void Main(string[] args)
{
//Creating an object 'list' derived from ArrayList class
ArrayList list = new ArrayList(16);

//Insertin value 1 and 2 to arraylist 'list'
list.Add(1);
list.Add(2);

//Accessing the value in an Arraylist 'list'
//displaying value 1 and 2 on the screen

Console.WriteLine(list[0]);
Console.WriteLine(list[1] + "\n");

//Creating an integer array a
int[] a = new int[10];

//Inserting a value 10,20,30 to array 'a'
a[0] = 10;
a[1] = 20;
a[2] = 30;

//Adding range of elements from array 'a' to Arraylist 'list'
list.AddRange(a);

//Displaying the value of Arraylist list using foreach()

foreach (object getList in list)
{
Console.WriteLine(getList);
}

//Getting the capacity of an Arraylist 'list'
//It will display 16 as it was specified.

Console.WriteLine("Capacity of list: " + list.Capacity);
Console.ReadKey();
}
}
}


c# Jagged Arrays

By The Saint on Thursday, January 29, 2009

comments (0)

Filed Under:

c# Jagged Arrays
When you create a multidimensional array, you always create a structure that has the same number of elements in each of the rows. For example, look at the following array declaration:

int[,] month = new int[12,30]; //Day of each month

This array assumes each row (month) has the same number of elements (days), when we know that some months have 30 days, some have 31, and one month has 29. With the array we’ve just declared, there will be several empty elements in the array. This isn’t much of a problem for this array, but with a much larger array we end up with a lot of wasted space.

The solution to this problem is to use a jagged array instead of a twodimensional array. A jagged array is an array of arrays where each row of an array is made up of an array. Each dimension of a jagged array is a onedimensional array.We call it a “jagged” array because the number of elements in each row may be different. A picture of a jagged array would not be square or rectangular, but would have uneven or jagged edges.

A jagged array is declared by putting two sets of parentheses after the array variable name. The first set of parentheses indicates the number of rows in the array. The second set of parentheses is left blank. This marks the place for the one-dimensional array that is stored in each row. Normally, the number of rows is set in an initialization list in the declaration statement, like this:

int[][] month = new int[12][];

This statement looks strange, but makes sense when you break it down. jagged is an Integer array of 12 elements, where each of the elements is also an Integer array. The initialization list is actually just the initialization for the rows of the array, indicating that each row element is an array of 12 elements, with each element initialized to the default value.

To initialize the size n element of the inner array:

month[0] = new int[31]; // for the month of Jan
month[1] = new int[29]; // for the month of Feb
month[2] = new int[31]; // for the month of Mar
. . .
month[11] = new int[31]; // for the month of Dec



Once the jagged array is declared, the elements of the individual row arrays can be assigned values. The following code fragment assigns values to jaggedArray:

month[0][0] = 23;
month[0][1] = 13;
. . .
month[7][5] = 45;

The first set of parentheses indicates the row number and the second set indicates the element of the row array. The first statement accesses the first element of the first array, the second element access the second element of the first array, and the third statement accesses the sixth element of the eighth array.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArraysBlogs
{
class Program
{
static void Main(string[] args)
{
int[][] month = new int[12][];

month[0] = new int[31];
month[1] = new int[29];
month[2] = new int[31];

//Inserting a values in jagged Array

month[0][0] = 25;
month[0][1] = 50;
month[0][2] = 75;
month[1][0] = 85;
month[1][1] = 95;
month[1][2] = 105;

//Accessing the values in jagged Array
Console.WriteLine(month[0][0]);
Console.WriteLine(month[0][1]);
Console.WriteLine(month[0][2]);
Console.WriteLine(month[1][0]);
Console.WriteLine(month[1][1]);
Console.WriteLine(month[1][2]);

Console.ReadKey();
}
}
}



C# linked list tutorial | linked list in C#

By The Saint on Monday, January 12, 2009

comments (0)

Filed Under:

C# Linked List Tutorial | linked list in C#
In our everyday life we encounter list: creating a list for a day-to-day task, a list for our favorite songs and name in our phonebooks. In this sample tutorial we will look at one particular type of list, the linked list. A.Net framework contains list-based collection classes, but linked list was not considered as part of the framework library. These tutorials will explain to you why linked list is needed in the program, a sample code of an object based linked list and array-based linked list.

How Arrays described?
Array is considered as the simplest form of data structure when storing multiple data in your program. Insertion and retrieving of data can be done easily by just specifying its index when invoking an array. Array is already part of the language so it does not require extra memory and processing time when it is used in the program.

Major drawbacks of Arrays
Common drawbacks in using static arrays are that, it lacks the flexibility to handle data that grows dynamically during runtime, searching of elements in unsorted array element is dawdling or slow for it has possibly visits the entire element in the array. Addition and deletion of elements is quite difficult for it has to shift the elements to avoid errors.

What is Linked List?
A linked list is a collection of class objects called nodes that have the characteristic to grow and shrink during runtime. Each node is linked to its successor node in the list using a reference to the successor node. A node is made up of a field for storing data and the field for the node reference. The reference to another node is called a link.

Comparing Linked list to an Array
A major difference between an array and a linked list is that the elements of a linked list are referenced by their relationship to the other elements of the array, whereas the elements in an array are referenced by position (the index).

AN OBJECT-ORIENTED LINKED LIST
In designing an Object-Oriented linked list involves at least two classes: A Node class and a node object instantiated to a Node Class each time we add a node to the list. The nodes in the list are connected via references to other nodes through an element called pointer which holds the address of the next node object. These references are set using methods created in a separate Linked List class.

Element of a Node Class
A Node Class is consists of different elements or fields these are: Data field and Pointer or address field. A Data field holds the actual data of a Node object while pointer field holds the address node of the next node object in the list. Purpose of this is to link the nodes in a list.

This is what linked list look like after inserting values (21-24).

This example will show you how it is done, just copy and past the source code on your program.

Here’s a sample code of a node class. (Filename: Node.cs)

using System;

namespace LinkedListSample{

class Node
{
private Node _next;
private object _data;

public Node()
{
_next = null;
}
public Node next
{
get
{
return _next;
}
set
{
_next = value;
}
}
public object data
{
get
{
return _data;
}
set
{
_data = value;
}
}
}
}


Single Linked List Class (Filename: SLL.cs)

using System;
using System.Collections;

namespace LinkedListSample{

public class SingleLinkedList
{
private Node head;
private Node tracer;

public SingleLinkedList()
{
head = null;
tracer = null;
}
public void insertNode(object data)
{
if(head==null)
{
head = new Node();
tracer = head;
head.data = data;
}
else
{
Node tempNode = new Node();
tempNode.data = data;
tracer.next = tempNode;
tracer = tempNode;
}
}
public void deleteNode(object data)
{
Node temp;
temp = head;

if(head.data.ToString() == data.ToString())
{
head = head.next;
temp = head;
}
else
{
while(temp != null && temp.next != null)
{
if(temp.next.data.ToString() == data.ToString())
{
temp.next = temp.next.next;
if(temp.next == null)
{
tracer = temp;
}
}
temp = temp.next;
}
}
}
public void traverse()
{
Node temp = head;


while (temp != null)
{
Console.Write(temp.data + " ");
temp = temp.next;
}
}
}

}




Linked List Implementation. (Filename: Main.cs)

using System;

namespace LinkedListSample{
class Program
{
public static void Main(string[] args)
{
// TODO: Implement Functionality Here
SingleLinkedList list = new SingleLinkedList();
int data=0;
Console.WriteLine("Insert node: 21, 22, 23, 24, 25 ");
list.insertNode(21);
list.insertNode(22);
list.insertNode(23);
list.insertNode(24);
list.insertNode(25);
list.insertNode(27);
Console.WriteLine("Output after insertion: ");
list.traverse();
Console.WriteLine("\n\nDelete Node 24: ");
Console.WriteLine("Output after deletion: ");
list.deleteNode(24);
list.traverse();
Console.WriteLine("\n\nDelete Node 22: ");
Console.WriteLine("Output after deletion: ");
list.deleteNode(22);
list.traverse();
Console.WriteLine("\n\nInsert node: 26 ");
list.insertNode(26);
Console.WriteLine("Output after insertion: ");
list.traverse();
Console.WriteLine("\n");
}
}
}

A simple C# program displaying "Hello world" on screen

By The Saint on Tuesday, January 06, 2009

comments (0)

Filed Under:

A simple C# program displaying "Hello World" on screen

The following console program stated below will simply display a string hello world on screen.


using System; //using keyword
used to import a library


namespace SampleCode{ //namespace denotes the project name

class HelloWorld{ //HelloWorld the name of the class
static void Main(string [] args){ //invoking the Main method

Console.WriteLine("Hello World"); //method used to display
the string
Hello world
}

}

}