Archive

Archive for the ‘Programming’ Category

C# Tutorial : Lesson 06 – Creating Value Types & Reference Types – Part I

July 23rd, 2007
Value Types & Reference Types

In C#, Variables are either value types or reference types depending on what they store, values or references. By reference we imply that the variable holds the memory address of another location where the actual value is stored. All built in data types – Int, Char, String, Float, Boolean, etc are value types while classes are reference types. The following is a diagrammatic representation of these two types.

In this picture there are two variables Num1 and Num2. Both of these being integer variables store the values directly.

The two variables in this case are actually objects of a car class. As you can see, they do not store the values directly but only a pointer to the memory location where the value is actually stored.

Consider the following code snippet:-

1
2
3
4
5
6
int Num1, Num2;
Num1 = 100;
Num2 = Num1;
Num1 ++;
Console.WriteLine("Num1={0}", Num1);
Console.WriteLine("Num2={0}", Num2);

Here we declare two integer variables, Num1 and Num2. On line 2 we set the value of Num1 to 100 and at line 3, we copy the value of Num1 to Num2. Both Num1 and Num2 now store 100. In the next line, we increment the value of Num1 by 1, thus it stores 101 now. This doesn’t make any change in the value of Num2 as both of them are value types and have a separate storage location in the memory. Finally, we display the numbers and the output comes as:-

Num1=101
Num2=100

Now take a look at this code snippet:-

1
2
3
4
5
6
Car Ferrari, McLaren;
Ferrari = new Car("F2004");
McLaren = Ferrari;
McLaren.Model = "F2002";
Console.WriteLine("Ferrari={0}", Ferrari.Model);
Console.WriteLine("McLaren={0}", McLaren.Model);

Two objects of the Car class are declared. We instantiate Ferrari by using the new keyword, passing the value F2004 to its constructor which sets the Model to F2004. The third line McLaren = Ferrari; copies the value stored by the object Ferrari to McLaren. All classes being reference types, the objects store the memory address of the actual storage location. Hence, by copying Ferrari to McLaren, we are actually copying the memory location. Now both Ferrari & McLaren are pointing to the same physical location in the memory. In the next line, the model for the McLaren is changed to F2002. This doesn’t make any change to the value stored by the McLaren object, i.e the memory address. The change occurs in the storage location pointed to by the McLaren object. Since, Ferrari is pointing to the same memory location this change reflects there as well and the results of the last two lines are:-

Ferrari=F2002
McLaren=F2002

Structures

A structure is a value data type which is used to group related heterogeneous data types. Say you want to store the details of all the employees of your company such as – Name, Post, Salary, Joining Date, etc. In such a scenario we can create a structure named employee which would be composed of these fields. We use the struct keyword to create structures with the following syntax:-

struct StructureName
{
member variable 1
member variable 2

}

Structures are similar to classes in the sense that they contain data members and functions, have access specifiers and need to be instantiated, but they do have notable differences such as:-

  • Structures are value types whereas classes are reference types
  • Structures can not be inherited
  • They cannot have default constructor

Example Usage:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct Employee
{
	public string Name;
	public string Post;
	public int Salary;
	public string JoiningDate;
}
static void Main(string[] args)
{
	Employee Emp1 = new Employee();
	Console.WriteLine("Enter Employee's Name");
	Emp1.Name = Console.ReadLine();
	Console.WriteLine("Enter Employee's Post");
	Emp1.Post = Console.ReadLine();
	Console.WriteLine("Enter Employee's Salary");
	Emp1.Salary = Console.ReadLine();
	Console.WriteLine("Enter Employee's Joining Date");
	Emp1.JoiningDate = Console.ReadLine();
}

Note: Unlike in other languages such as C/C , structures in C# can have member functions.

Enumeration

Enumeration is another value data type that we use to store non generic values such as the name of the day – Sunday, Monday, etc. One may question the need for enumeration considering that we can use the string data type to store the names. But, one could assign just about any value to the day, which we certainly don’t want. We could also use the numbers from 0 – 6 to denote the 7 days. However, that doesn’t clarify whether 0 is for Sunday or Saturday. The enum keyword is used to create an enumerated data type with the following syntax:-

enum EnumDataType { Value1, Value2, and so on }

Example usage:-

1
2
3
4
5
6
enum Month { Jan, Feb, Mar, Apr, May, Jun, Aug, Sep, Oct, Nov, Dec };
static void Main(string[] args)
{
	Month ThisMonth;
	ThisMonth = Month.May;
}

Note:- The values of an enumerated data type are assigned in design time and not at runtime using the Console.Read or Console.ReadLine method.

Arrays

An array is a collection of values of the same data type, grouped under the same name and referred to by their distinct indexes. This is how they are represented in the memory.

Declaration

Syntax:-

datatype[] ArrayName;

  • Where datatype is the type of data that the array will store – int, string, char, etc.
  • [] Specifies the size of the array.
  • ArrayName is the name with which we would be using the array.
  • Example usage:-

    int[] Marks;

    Initialization
    Memory is allocated to the array only when it is instantiated. The instantiation can be done in the following methods. Once initialized a default value is assigned to all of the elements depending on their data type – 0 for int, “” (NULL String) for char or string, etc.

    Syntax:-

    ArrayName = new datatype[size];

    This step can be done along with the declaration.

    datatype[] ArrayName = new datatype[size];

    Example Usage:-

    int[] Marks = new int[10];

    Note: This creates 10 elements starting from 0 to 9

    Assigning values
    Each element of the array can be accessed by specifying their index along with the ArrayName.

    ArrayName[index] = value;

    Example:-

    Marks[5] = 99;

    Values can also be assigned during declaration as follows:-

    datatype[] ArrayName = {value1, value2, value3 and so on};

    Example:-

    int[] Marks = {100, 13, 69, 99};

    Using this process implicitly sets the size for the array. In this case it would be 4. The elements can be accessed by their indexes starting from 0 to 3. Note: In C# Index always starts at 0.

    Using the following is equivalent to using the above line of code.

    int[] Marks = int[4] {100, 13, 69, 99};

    Copying an Array
    You can copy an array just as easily you copy other variables. Example:-

    1
    2
    
    int[] Source = {0, 1 , 2, 3, 4};
    int[]Destination = Source;

    One point to note is that an array being a reference type, both these arrays point to the same location in memory and any change made in either of them would be reflected in the other one as well. To make separate copies of the array, we need to copy each of the elements individually. The code below does just that.

    1
    2
    3
    4
    5
    6
    
    int[] Source = { 0, 1, 2, 3 };
    int[] Destination = new int[Source.Length]; // Set the size of the destination to be the same as that of the source
    for (int I = 0; I < Source.Length; I  )
    {
    	Destination[I] = Source[I];
    }

    This step can be done along with the declaration.

    datatype[] ArrayName = new datatype[size];

    Example Usage:-

    int[] Marks = new int[10];

    Note: This creates 10 elements starting from 0 to 9

    C#

C# Tutorial : Lesson 05 – Encapsulation & Abstraction

April 9th, 2007
Encapsulation & Abstraction

Two concepts that go together in the object oriented approach are Encapsulation & Abstraction. Abstraction is the representation of only the essential features of an object, while Encapsulation is the hiding of the non-essential features.

Think of a person driving a car. He does not need to know the internal working of the engine or the way gear changes work, to be able to drive the car (Encapsulation). Instead, he needs to know things such as how much turning the steering wheel needs, etc (Abstraction).

Consider the example from the programmer’s perspective who wants to allow the user to add items to a list. The user only needs to click a button to add an item (Abstraction). The mechanism of how the item is added to the list is not essential for him (Encapsulation).

Below is a graphical representation of Encapsulation for the car class.

Implementing Encapsulation & Abstraction

Consider the countless advertisements being bombarded to viewers. The viewer does not listen to each one of them, rather only those he?s curious about. We use access specifiers to restrict the scope (visibility) of the class members.

Types of Access Specifiers
  • public – The members (Functions & Variables) declared as public can be accessed from anywhere.
  • private – Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;
  • protected – Protected members can be accessed only from the child classes.
  • internal – Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.

    Both these classes are equivalent.

    1
    2
    3
    4
    
    class MyClass
    {
     
    }
    1
    2
    3
    4
    
    internal class MyClass
    {
     
    }
  • protected internal – Similar to protected, protected internal members can be accessed from the child classes but only within the application.

Note: The members are always accessible to its own member functions, irrespective of the access specifier.

Lets see an example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class House
{
	// Data Members
	public string DrawingRoom;
	private string Kitchen;
 
	// Member Functions
	private bool EnterDrawingRoom()
	{
		DrawingRoom = "The Drawing Room";
	}
 
	public bool EnterKitchen()
	{
		Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function
		can modify it because the member function itself has access to all other members. */
	}
 
}
 
class MainClass
{
	public static void Main()
	{
		House TheBlackHouse = new House();
		TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible
		from outside the class */
		TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible
		 from outside the class. */
		TheBlackHouse.EnterDrawingRoom(); /* Error - Private Member Function is not accessible
		// from outside the class. */
		TheBlackHouse.EnterKitchen(); /* OK - Public Data Member is accessible from outside
		the class. */
	}
}

Lets study the code. Inside the main function we declare an object TheBlackHouse of the House class. Thereafter, we set the value of the data member DrawingRoom for TheBlackHouse to “Main Drawing Room”. Since, DrawingRoom is declared as public, the above step works without any error. On the next line, TheBlackHouse.Kitchen = “Main Kitchen”; we are trying to assign the value “Main Kitchen” to the Kitchen variable of TheBlackHouse object. However, Kitchen is declared as private. Hence, this step generates an error.

In the next line, we are trying to call the private method EnterDrawingRoom for the object. This generates an error as well. Finally, we are calling the EnterKitchen function which is declared as public. Notice that inside the EnterKitchen function, we are assigning the value “The Kitchen” to the private variable Kitchen. This does not generate an error because the EnterKitchen method belongs to the same class and it has access to all the members inside the class, irrespective of the access specifier.

Why do we need Encapsulation, Abstraction?

Programming is all about concepts, different from coding where we basically translate the logic to language specific codes. When given a problem statement, there might be a number of ways to solve it. The logic devised to solve it will depend of the programmer. What we must learn to implement is the most efficient approach; efficient in terms of time, memory & cost. Object oriented methodologies such as these are what allow us to maintain efficiency.

By using encapsulation & abstraction, we reduce complexity by ignoring unimportant details and we maintain effectiveness by representing important ones.

C#

C# Tutorial : Lesson 04 – Object Oriented Programming

April 9th, 2007
Object Oriented Programming

Object Oriented Programming is a methodology modeled on real life. It comprises of the basic unit, an object, being used in implementing a program. Think of all the objects around you – cars, buses, birds, trees, etc. You will find countless ones of them, everywhere you go. In order to tackle this huge number, we started classifying them, thus came the term Class.

Class

A class is a composition of the theoretic characteristics (attributes and properties) of an object and the things it can do – behaviors, methods and features. Take the Car as an example. Its characteristics can include speed, color, number of gears, etc and it exhibits behaviors such as accelerate, brake and gear-change.

Object

An object is an instance of a class. Consider the Car class above, the Aston Martin that was used in the movie – Die another Day is an object of the car class. One point to note is that each object has at least one attribute that makes it unique.

Message Passing

Objects do not exist in isolation. They interact with other objects. These interactions take place through messages. Message passing is the process by which an object (sender) sends data to another object (receiver) or asks the other object to invoke a method. Thus, each message has a sender and a receiver.

Behavior

It is how an object acts and reacts, in terms of its state changes and message passing. For example, when the driver applies the break, the car comes to a stop.

This was all about the object oriented methodology. Now, let us take a look on how OOP is used in C#

Declaring Classes

We declare classes using the following syntax:-

class < Class Name >
{

data members…

member functions…

}

Here class is a keyword. Class name can be anything that follows the naming rules.

Rules for naming classes
  • A class name must begin with a letter & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the class name.
  • A class name must not be the same as a reserved keyword such as using, public, etc.

Conventions for naming classes

  • Class Name must be meaningful, ideally a noun.
  • Naming of classes can be done using either the Pascal case, where the first character is capital and the rest are in small letters or using the Camel Case in which the first letter is in small case but the first letter of each successive word is in caps. Example:-
    • Pascal Case: Classone
    • Camel Case: classOne

The conventions are not mandatory but best practices, abiding by which allows others to easily understand our code.

Data members are the variables or other objects declared inside the class while member functions are the functions declared in it.

Example Class:-

class Student
{
	// Data Members
	public string Name;
	public int Age;
 
	// Member Function
	public void Display()
	{
		Console.WriteLine("Name {0}\n Age {1}", Name, Age);
	}
}

The public access specifier has been used in order to allow the data members & functions to be visible from outside the class. The access specifiers will be explained in the forthcoming tutorials.

Declaring & Instantiating Objects

Creating objects is similar to declaring variables and can be done using the syntax:-

<Class Name> <Object Name>;

Example: Student S1;

Before we start using the object, we need to instantiate it. Instantiation involves memory allocation and other basic initializations contained in the object’s constructor. We use the new keyword to instantiate objects. The syntax for which is given below:-

Note: Constructor is a special member function of a class that is used to initialize the data members. It will be dealt with, in later tutorials.

<Object Name> = new <Class Name>;

Example Usage: S1 = new Student();

These two steps can be done in a single line of code as Student S1 = new Student();

Using the Objects

We use the . (Dot) operator to access the members of the object. For example, to call the display method for the student class’s S1 object we write S1.Display();

Data members can be accessed in the similar fashion S1.Name = “Kenshin Himura”;

Releasing Memory

To release the memory occupied by the object we use S1 = null;

Example Program:-

using System;
 
namespace CSTutorials
{
	class Student
	{
		// Data Members
		public string Name;
		public int Age;
 
		// Member Function
		public void Display()
		{
			Console.WriteLine("Name {0}\n Age {1}", Name, Age);
		}
	}
 
	class Program
	{
		static void Main(string[] args)
		{
			Student S1;			 // Declaration
			S1 = new Student();	 // Instantiation
 
			Student S2 = new Student();	 // Single line Declaration &amp; Instantiation
 
			// Assigning value to member variables
			S1.Name = "Michael";
			S1.Age = 37;
 
			S2.Name = "Kimi";
			S2.Age = 25;
 
			// Invoking member function
			S1.Display();
			S2.Display();
			Console.ReadLine();
		}
	}
 
}
Benefits of Object Oriented Programming
  • Realistic Modeling: Living in a ‘World of Objects’, the model built on real life is a much better approach because it allows issues to be tackled with greater accuracy.
  • Re-usability of code: Think of a scenario where a car making company specialized in two seater’s decides to launch a four seater model. Converting the two seater model to a four seater is easier than designing a new model altogether.
  • Resilience to change: Being compartmentalized, individual objects can be improved without having to re-package the entire software.
  • Polymorphism: The behavior of an object can depend upon the state its in, thus exhibiting Polymorphism. Consider a car colliding with a wall. The impact of the process would depend upon the approach speed of the car, the Angle it strikes in, the strength of the wall and so on. If two cars were to collide, the results would be much different, with both of them receiving considerable damage.

C#

C# Tutorial : Lesson 03 – Programming Constructs

April 9th, 2007
Conditional Branching

By branching we imply, having different paths for execution. Conditions are used to determine which statements need to be executed. Suppose, you have a program to store the details of employees. Depending upon the post of the employee, there would be various fields associated with it. A department head, for example, would have a property denoting the department he heads, etc. We use conditional branching in such a scenario.

C# provides the following conditional constructs:-

if .. else

Syntax:-
if (<condition>)
{
statements
}
else
{
statements
}

The else part is optional and can be omitted. The working of if .. else construct is very simple and follows the pattern – If this is true I’ll do that or else I’ll do something else. The statements included within the if block are executed when the condition specified in if, is true, otherwise the statements inside the else block are executed. In case, there is no else statement, the execution flow continues to the proceeding statements.

Here’s an example:-

1
2
3
4
5
6
7
8
9
10
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age < 18)
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

Lets step through the code. Line 1 displays a message Enter your age. At line 2, the age entered by the user is read using ReadLine() (as a string) and converted to an integer using the ToInt32 function. Finally the value is stored in the integer variable Age. When the execution reaches line 3, the expression inside if is evaluated. If the user supplied an age less than 18, the execution flow would move to line 5 – Console.WriteLine(“You are not permitted in here.”); and the message You are not permitted in here would be displayed. In the other scenario, when the age would be either equal to or greater than 18, line 7 would be executed and the message You may come in will be displayed.

The condition inside the if statement can be composed of a complex expression chained by the logical operators. For Example:-

1
2
3
4
5
6
7
8
9
10
11
12
Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you with your guardian? (True/False)");
bool WithGuardian = Convert.ToBoolean(Console.ReadLine());
if ((Age < 18 ) && (WithGuardian == false))
{
	Console.WriteLine("You are not permitted in here.");
}
else
{
	Console.WriteLine("You may come in.");
}

At line 4 the user’s response of whether he/she is with a guardian would be stored inside the boolean variable WithGuardian. Notice that ToBoolean function is used to convert the input to boolean (True/False) value. At line 5, the complex expression will be evaluated. The expression is made up of two sub-expressions: Age < 18 and WithGuardian == false. These two expressions are joined with the logical AND operator (&&). Therefore, when both of the expressions amount to true, the entire expression would evaluate to true and the message – You are not permitted in here will be displayed. For any other combination, the final expression would be equivalent to false and the message – You may come in will be displayed.

A number of conditions can be chained by using else if as follows:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Console.WriteLine("Enter your salary");
int Salary = Convert.ToInt32(Console.ReadLine());
if (Salary > 250000)
{
	Console.WriteLine("Welcome Mr. CEO");
}
else if (Salary > 200000)
{
	Console.WriteLine("Welcome Mr. Chairman");
}
else if (Salary > 0)
{
	Console.WriteLine("Welcome Programmer");
}
else
{
	Console.WriteLine("Welcome dear Customer");
}

In this case, if the salary supplied by the user is greater than 250000, the message – Welcome Mr. CEO will be displayed otherwise if the Salary is greater than 2000000 then the output will be Welcome Mr. Chairman else if the salary is greater than 0, the message – Welcome Programmer will be displayed. For any other value (Salary less than 1), the statements inside the else block would be executed and Welcome dear Customer will be the output.

switch .. case Construct

Switch case facilitates easy branching when the condition is pertaining to a single expression. Each supplied Value is preceded by a case construct.

Syntax:-
switch (<expression>)
{
case Expression_1;
statements
break;

case Expression_2;
statements
break;

}

break is a C# keyword, which is used to exit the body of a switch, for or while loop. Equivalent to the else construct is the default case. Statements within the default case are executed when no other condition holds true.

Example:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
Console.WriteLine("Enter the month (mm)");
int Month = Convert.ToInt32(Console.ReadLine());
switch (Month)
{
	case 1:
		Console.WriteLine("January");
		break;
 
	case 2:
		Console.WriteLine("February");
		break;
 
	case 3:
		Console.WriteLine("March");
		break;
 
	case 4:
		Console.WriteLine("April");
		break;
 
	case 5:
		Console.WriteLine("May");
		break;
 
	case 6:
		Console.WriteLine("June");
		break;
 
	case 7:
		Console.WriteLine("July");
		break;
 
	case 8:
		Console.WriteLine("August");
		break;
 
	case 9:
		Console.WriteLine("September");
		break;
 
	case 10:
		Console.WriteLine("October");
		break;
 
	case 11:
		Console.WriteLine("November");
		break;
 
	case 12:
		Console.WriteLine("December");
		break;
 
	default:
		Console.WriteLine("There are only 12 Months.");
		break;
}

Depending on the value entered by the user (1-12), the appropriate month will be displayed. For any other value, the default case will be executed and the message There are only 12 Months. will be displayed.

Multiple Values can be made to lead to the same block of statements by excluding the break statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Console.WriteLine("Enter a number  (1-10)");
int Num = Convert.ToInt32(Console.ReadLine());
switch (Num)
{
	case 2:
	case 3:
	case 5:
	case 7:
		Console.WriteLine("The number is prime.");
		break;
	case 1:
	case 9:
		Console.WriteLine("The number is odd.");
		break;
	case 4:
	case 6:
	case 8:
		Console.WriteLine("The number is Even");
		break;
	default:
		Console.WriteLine("The number is not in range.");
		break;
}
Looping

A Set of instructions that are repeated is called a loop. Suppose you want to print numbers from 1 – 10. You could do that using Console.WriteLine statement for each of the 10 numbers. But, what if you had to print numbers from 1 – 1000? Using the computer’s iterative power is a much better approach.

C# supports 3 kinds of loops which are discussed below:-

The for loop

This loop is generally used for arithmetic operations, where we are aware of the starting and end point of the loop. Syntax of for loop is as follows:-

for(<initialization>;<condition>;<increment/decrement>)
{
statements
}

To print numbers within a range, say 1 – 1000, we declare a counter variable (preferably single character variable like I), initialize it to the starting number (1) and keep incrementing its value by 1 until the number exceeds the end point (1000). Off course, we would have the body of the loop where the operation would be done, in this case, displaying the numbers on screen.

1
2
3
4
for(int I = 1; I <= 1000; I  )
{
	Console.WriteLine(I);
}

Lets break the for statement down:-
Initialization: int I = 1
Condition: I <= 1000
Increment: I

All the parts here are optional and can be left out. So, you can initialize the variable I, above the for statement and leave out the initialization block. The code would look like this (; I <= 1000; I ). Similarly, you could remove the condition part to make the loop infinite or you can include the increment statement within the body of the for statement itself (inside the { and } brackets).

Another variation of a for statement is the empty loop which does not contain any body:-

for(int I = 1; I <= 1000; I++);

Such a for statement is followed by the semicolon.

The while loop

The for loop cannot be used when the range of the loop is unknown (Well, actually it can, but the approach would not be logical). Say, you want to continue inputting values from the user as long he wishes to. This can be easily implemented by the while statement.

Syntax:-
while(<condition>)
{
statements
}

We don’t have initialization and increment/decrement slot over here. These need to be implemented additionally. Take a look at the code snippet below.

1
2
3
4
5
6
7
8
9
bool Continue = true;
while(Continue == true)
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}

We have declared a boolean variable Continue which we use to check whether to continue repeating the process. It has been initialized to true, so that the loop is executed for the first time. The user’s choice of whether to continue with the loop or not, is stored in Continue. As long as the user enters true, the statements within the body of the while loop would keep on executing.

Anything that can be implemented using for loop, can also be done using the while loop. Below is the code to print numbers from 1 – 1000 using while.

1
2
3
4
5
6
int I = 1;
while(I <= 1000)
{
	Console.WriteLine(I);
	I++;
}
The do while loop

The do while loop is a variation of the while loop in which the condition is evaluated at the end of the loop. Thus, the loop is executed at least once. Recall the first while program we did. The bool variable continue stores the user’s choice. However, for the first iteration, it does not store the choice. In such a scenario, we had to initialize continue with the value true so that the loop is executed for the first time. A better approach would be to use the do while loop and check the condition at the end. The code for which is given below.

1
2
3
4
5
6
7
8
9
10
bool Continue;
do
{
	int A;
	Console.WriteLine("Please Enter a Number");
	A = Convert.ToInt32(Console.ReadLine());
	Console.WriteLine("Continue (True/False)");
	Continue = Convert.ToBoolean(Console.ReadLine());
}
while(Continue == true);

Note: The while part in the do while loop needs to be terminated with the semicolon.

Although, either of the three types of loops can be used to do an iteration, one needs to use the appropriate loop for the job. Use the for loop for arithmetic operations, while loop for non-arithmetic ones and the do-while loop when the loop must execute at least once.

C#

C# Tutorial : Lesson 02 – Variables & Operators

April 9th, 2007
Variables

A Variable is a named location that stores a value. Although variables are physically stored in the RAM, their actual memory address is not known to the programmer. We can use the variables via the name we give them. These are the rules for naming a variable:-

  • The name must begin with a letter or an underscore & can be followed by a sequence of letters (A-Z), digits (0-9) or underscore (_)
  • Special Characters such as ? – * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the variable name.
  • A variable name must not be the same as a reserved keyword such as using, public, etc.
  • The name can contain any number of the allowed characters
  • Variables with the same scope cannot have the same name

Note: C# being a case-sensitive language, two variables such as var1 and Var1 would be different.

Any Variable has a type associated with it, which basically restricts the type of value it can store. The table below shows the Data types available in C#, the size they occupy in the memory and the values they can contain.

Type Size Range of values
char 2 0 and 65536
int 4 -2,147,483,648 and 2,147,483,647
float 4 -3.402823E+38 and -1.401298E-45 (For Negative Values)
1.401298E-45 and 3.402823E+38 (For Positive values Values)
double 8 -1.79769313486232E308 and 4.94065645841247E-324 (For Negative Values)
4.94065645841247E-324 and 1.79769313486232E308 (For Positive values Values)
bool 1 true or false
string Depends on length of the string 0-2 million Unicode Characters


Variable Declaration

Before we can use a variable, we need to declare it. Declaration of variables are done using the syntax:-
<Data Type> <Variable Name>;

For Example:-

1
2
3
4
int Age;
char Sex;
string Name;
bool IsMarried;

Variables of the same data type can also be declared using the syntax:-
<Data Type> <Variable 1>, <Variable 2>, .. and so on;

Example:-

1
int Age, RollNum;
Initialization

While declaring a variable, it is possible to assign an initial value to it. This operation is called Initialization and it has the following syntax:-
<Data Type> <Variable Name> = <Value>;

Example:-

1
2
3
4
int Age = 20;
char Sex = 'M';
string Name = 'Max Steel';
bool IsMarried = false;

Multiple variables of the same data type can also be initialized in a single line of code using the syntax:-
<data type> <variable 1> = <value>, <variable 2> = <value>;

1
int Age = 20, RollNum = 69;
Value Types

Values can be stored in variables by two methods which are: by value and by reference. Value types store the supplied value directly in the memory whereas reference types store a reference to the memory where the actual value is located. The benefit of the reference type is that changes made to any alias of the variable will reflect across all of its aliases.

Accepting Values in Variables

To input values from the user at runtime, we use the Console.ReadLine() function. For Example:- string FirstName = Console.ReadLine(); The above statement would declare a string variable FirstName and store the value retrieved from the user in it.

Note: Console.ReadLine() returns value as a string. Therefore, one must use type casting to convert the value to the required type. We use the member functions of the Convert class to do this. For Example: int Age = Convert.ToInt32(Console.ReadLine());. Similarly, there are other functions such as ToChar(), ToString, etc for conversion to other data types.

Operators

Similar to mathematics, every programming language has its own set of operators, be it arithmetic or logical. Operators enable us to perform operations on 1 or more values (operands) and calculate the result.

Usage

Depending on the number of operands they take, operators can be either unary or binary.
The use of an operator takes one of the following form:-

Unary Usage

  • <Operator> <Operand>
    Example: ++A;
  • <Operand> <Operator>
    Example: A++;

Binary Usage

  • <Operand 1> <Operator> <Operand 2>
    Example: A + B;
Classification

The operators in C# can be classified as follows:-

Arithmetic operators – Just what the name suggests, these operators are used to perform arithmetic operations.

Operator Usage Utility Type
+ A + B Add two numbers Binary
- A – B Subtract a number from another Binary
* A * B Multiply two numbers Binary
/ A / B Divide a number with another Binary
% A % B Remainder of the operation A / B Binary

Arithmetic Assignment Operators – These can be considered as shortcuts as they are used to perform both arithmetic and assignment operations in a single step.

Operator Usage Utility Type
= A = 69 Store the value 69 into A Binary
+= A += B Equivalent to A = A + B Binary
-= A -= B Equivalent to A = A – B Binary
*= A *= B Equivalent to A = A * B Binary
/= A /= B Equivalent to A = A / B Binary
%= A %= B Equivalent to A = A % B Binary

Increment / Decrement Operators – These operators are used to increment or decrement the value of an operand by 1.

Operator Usage Utility Type
++ ++A or A++

Increments the value of A by 1

Unary
--
--A or A--
Decrements the value of A by 1 Unary

Difference between Pre & Post Increment/Decrement
Consider the following code snippet:-

1
2
3
int A = 0;
int B = A++;
int C = ++A;

At the very first line, we have used the Arithmetic Assignment operator, = to assign the value of 0 to A. In the proceeding lines we have used both Pre & Post increment. At line 2 int B = A++; the operation being post increment, the value of A i.e 0 is assigned to B followed by the increment of A’s value. At line 3 int C = ++A; the current value of A, i.e. 1 is incremented by 1 following which the new value of A is assigned to C. Therefore, the value of A = 2, B = 0 and C = 2.

What will be the output of the following code?

1
2
3
int A = 5;
int B = (A++) + (--A);
Console.WriteLine("Value of B = {0}", B);

At line, 1, A gets initialized to 5. The next line is a bit tricky. Here, The RHS should be evaluated like 5 + 4 because A++ is post increment and this operation should occur after the line of statement. But, this is not the case, instead it takes place in the same line but after the evaluation of the sub-expression (A++). Hence, the expression will be evaluated as 5 + 5 and the output will be 10.

Comparison Operators – These operators are to compare two values and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
< A < B

Compares if A is less than B

Binary
> A > B Compares if B is less than A Binary
<= A <= B Compares if A is less than or equal to B Binary
>= A >= B Compares if A is greater than or equal to B Binary
== A == B Compares if A is equal to B Binary
!= A != B Compares if A is not equal to B Binary

Logical Operators – These operators are used to perform logical operations and return the result as either ‘true’ or ‘false’.

Operator Usage Utility Type
&& A && B

Returns true if Both A and B are true

Binary
|| A || B Return true if either A or B are true Binary
! !A Returns True if A is false Unary
^ A ^ B Returns true when A and B do not match i.e one is true and the other is false Binary


Displaying Variables

We us the WriteLine method to display the value stored in variables.

Displaying Single Variable

1
2
int A = 6;
Console.WriteLine(A);

Displaying Multiple Variables

1
2
int A = 6, B = 9;
Console.WriteLine("{0},{1}", A, B);

Notice the code “{0},{1}”. This is the format for the output to be generated by WriteLine. Since, we are displaying two variables, we need to specify the format accordingly. Here {0} and {1} represent where the proceeding variables A & B will be displayed. Now take a look at the following code snippet:-

1
2
int A = 6, B = 9;
Console.WriteLine("The value of A = {0} and B = {1}", A, B);

The output of these lines would be: The value of A = 6 and B = 9. As you can see, the {0} and {1} are replaced by the variables A and B. 0 and 1 correspond to the index of the variables following the format, starting from 0.

Comments

Software applications are made by a group of coders. Each one of them handles various aspects of the application. Its important to write descriptive texts in order to help other coders understand, the mechanism of the codes you have written. We use comments denoted by // or /* and */ for this very purpose. Example usage:-

1
2
3
// This is a comment
/* These are two lines
of comments */

Note: The compiler ignores all comment entries. // is used for single line of comment while /* and */ are used for multiple lines.

What’s in a Semicolon?

Whitespace except when used inside quotes, is ignored in C#. All statements in C# are terminated by using the semicolon. This allow spanning of codes across multiple lines.

The following lines of code are functionally equivalent.

1
int A = 6, B = 9; Console.WriteLine("A   B = {0}", A   B); Console.ReadLine();
1
2
3
int A = 6, B = 9;
Console.WriteLine("The sum of {0} and {1} = {2}", A, B, A   B);
Console.ReadLine();

C# , ,

C# Tutorial : Lesson 01 – Hello World Program

February 14th, 2007

This is the first installment of my venture to explain the bits and pieces of C# that I have managed to learn at NIIT. In this lesson we would be creating the Hello World application.

First Step: Create a New Console Application in Visual C#

The IDE automatically adds the following code:-

1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Text;
 
namespace HelloWorld
{
	class Program
	{
		static void Main(string[] args)
		{
		}
	}
}

Lets take a look at the first 3 lines. All of these lines begin with the keyword using. A namespace is an abstract collection of classes. The .NET Framework has a huge set of classes. They are grouped under namespaces for easy accessibility, better categorization and to prevent name clashing. For Example, the System.IO namespace contains all the classes, functions & methods required for Input Output operations, thus making life easier for us human beings. While the namespaces have remarkable benefits, they tend to bring in some potential inconveniences too. Take the System.Console.WriteLine() method for example. The method has to be called along with its complete path in the hierarchy, a really tiresome process to do repeatedly. This is when the using keyword comes into aid by importing the namespaces. When imported, the classes inside the namespace can be accessed just by their names. So, once we have imported the System namespace, the above method can be called as Console.WriteLine().

Any .NET application that we make, has to reside in a namespace of its own, so we write the statement namespace HelloWorld. All the classes you create under this namespace can be accessed as NameSpaceName.ClassName.

Next we have the class declaration itself. Inside you’ll find the static void Main function. This is the entry point for the application. Think of it as the outer door of your house. Any one coming inside has to first pass through it. The entry point must be declared as static because that way the main function can be invoked even without creating an object of the Program class. Also the name of the entry function should be Main, the capital M counts too.

Any application can take parameters, when run from the command prompt. Say you ran the Notepad application as follows Notepad.exe MyFile.txt. The text MyFile.txt is the parameter passed to it, Notepad reads this parameter and opens the file. Similarly, we may need to work with arguments passed to our application. This is why we use the string[] args inside the Main function.

Up until this point I have described the auto generated code. Now let us type in some code of our own. Keeping with the tradition of the Hello World program we type in Console.WriteLine(“Hello World”); inside the body of the Main function. The Console class resides in the System namespace and represents the standard input, output and error streams for console application. The WriteLine method displays the supplied argument(s) on the console.

Press F5 to run the application. You’ll see a console window with the text Hello World appear. Don’t worry if the window closes on its own. Its because the application reaches the end point and exits. You can add the following line to make it halt for an input before exiting: Console.ReadLine();

This is how our final code looks like:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
using System.Collections.Generic;
using System.Text;
 
namespace HelloWorld
{
	class Program
	{
		static void Main(string] args)
		{
			Console.WriteLine("Hello World");
			Console.ReadLine();
		}
	}
}
Escape Sequences

Much like C/C++ , C# has a list of escape sequences. Escape Sequences or Escape Characters are some special characters which cannot be displayed directly. For Example, the newline character or the Double Quotes.

White space being ignored by C#, the newline escape sequence is the only way to display the newline character in the output. The double quotes are used to enclose strings hence they cannot be used directly. To display the special characters such as these, we use escape sequences. All escape sequences begin with the backslash character \

Example Usage:-

Console.WriteLine("This is a \n multi-line text");

Output:-
This is a
multi-line text

Console.WriteLine("C# is a \"Programming Language\"");

Output:-
C# is a “Programming Language”

Here’s the list of the escape characters in C#

Escape Sequence Equivalent Character
\’ Single Quotation
\” Double Quotation
\\ Backslash
\0 NULL
\a Alert
\b Backspace
\f Form Feed
\n New Line
\r Carriage Return
\t Horizontal Tab
\v Vertical Tab

Note: Equivalent for Visual Basic’s vbCrLf is \r\n

C#

Non Repeating – Random Number Generation Class

February 8th, 2007

Sometimes, we require to generate non-repeating random numbers. Here’s the code I wrote to do just that. The numbers to be generated can be within the specified range or passed as a param array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Public Class RandomNumber
    Dim NumDomain As New ArrayList      ' The Numbers to be generated
    Dim Nums As New ArrayList           ' The Numbers waiting to be generated
 
    Sub New(ByVal Start As Integer, ByVal Finish As Integer)
        ' Sequential Numbers
        Dim I As Integer
        For I = Start To Finish
            NumDomain.Add(I)
        Next
 
        AddItems()
    End Sub
 
    Sub New(ByVal ParamArray Numbers() As Integer)
        ' Numbers in a Param Array
        Dim Number As Integer
        For Each Number In Numbers
            NumDomain.Add(Number)
        Next
 
        AddItems()
    End Sub
 
    Private Sub AddItems()
 
        Nums.Clear()
        ' Insert All Numbers Into the Array
        Dim I As Integer
        For I = 0 To NumDomain.Count - 1
            Nums.Add(NumDomain(I))
        Next
    End Sub
 
    Public Function GetRandomNumber() As Integer
        If Nums.Count = 0 Then
            ' Re-add the Items, when all the numbers have been generated.
            AddItems()
        End If
 
        ' Return a Random Item and Remove it from the List
        Dim Ch As Integer
 
        ' Using Timer as the seed for the Random Number Generation
        Randomize(Microsoft.VisualBasic.Timer)
 
        ' Random Number is generated within the range.
        Ch = 0 + CInt(Rnd() * (Nums.Count - 1))
 
        Dim Num As Integer = Nums(Ch)
        Nums.RemoveAt(Ch)
        Return Num
    End Function
End Class
Mechanism

The overloaded constructors allow numbers to be generated either within a range or from the numbers passed as parameters. Internally there are two array lists: NumDomain & Num. The former contains all the numbers within the domain and the latter holds the numbers that have not been generated. The GetRandomNumber function returns a random number from the Num array list and also removes it from there. When all the numbers have been poped (not to be confused with stack poping) out, the Num array list is re-filled with the values in NumDomain and the cycle continues. Thus, allowing no repeats per cycle.

Visual Basic