Tuesday, March 30, 2010

Arithmetic assignment Operators:

Using Operates:

The sixth part of the C# Fundamentals tutorial describes the basic arithmetic operators available to the C# programmer. These operators allow general algebraic operations to be carried out against numeric data type values.

Outputting Numeric Values:

Before we begin the examination of the arithmetic operators we will take a brief aside. So far in the C# Fundamentals tutorial there has been no discussion of outputting numeric values to the screen. As we are about to start modifying the values in variables, it is important to be able to view the results of the operations.

In the first part of the C# Fundamentals tutorial, a console application was created and the console was outputted to using the Console.WriteLine command. The Console.WriteLine command may also be used to output numeric data types.
For example:

int quantity = 5;
Console.WriteLine(quantity); // Outputs 5

You can use the Console.WriteLine command to test the examples provided in the following sections

Basic Arithmetic Operators:

There are five basic arithmetic operators available to the C# developer. These are used for addition (+), subtraction (-), multiplication (*), division (/) and modulus (%). Of these, the first four are available to almost every programming language.
Here are some simple examples:

int a = 6;
int b = 3;
int result;

result = a + b; // result = 9
result = a - b; // result = 3
result = a * b; // result = 18
result = a / b; // result = 2
result = a + b - 1; // result = 8
It is important to remember that the resultant value of a mathematical operation is subject to the rules of the receiving variable's data type. The result of a division operation may yield a floating point value. However, if this is assigned to an integer then the fractional part will be truncated. Equally important, and less obvious, is the effect of an operation performed on several integers and assigned to a non-integer. In this case, the result is calculated as an integer before being implicitly converted. This means that although the resultant value is assigned to a floating point variable, the fractional part is still truncated unless at least one of the values is explicitly converted first.
The following examples illustrate this:

int a = 7;
int b = 3;
int integerResult;
float floatResult;

integerResult = a / b; // integerResult = 2 (truncated)
floatResult = a / b; // floatResult = 2.0 (truncated)
floatResult = (float)a / b; // floatResult = 2.33333325

The last of the basic arithmetic operators is modulus. The modulus operator yields a value equal to the remainder of an integer division. As an example, when ten is divided by three the answer is three with a remainder of one. One is the modulus value. The modulus value can be used with both integer and floating point data types

int a = 10;
int b = 3;
float c = 3.5F;
int integerResult;
float floatResult;

integerResult = a % b; // integerResult = 1
floatResult = a % b; // floatResult = 1.0
floatResult = a % c; // floatResult = 3.0

Increment and Decrement Operators:

C# provides two operators that can be used to increase or decrease a variable's value by one. These are the increment operator (++) and the decrement operator (--). The increment and decrement operators are known as unary operators because they are applied to a single value. The operators can be placed before the variable to be adjusted (prefix) or after it (postfix) for similar results.

// All of these commands add one to the variable "a"
a = a + 1;
++a; // prefix
a++; // postfix

// All of these commands subtract one from the variable "a"
a = a - 1;
--a;
a--;
The above examples give the impression that the prefix and postfix varieties of the increment and decrement operators yield the same results. This is true in the simple scenarios examined so far. However, when the operators are used as a part of a more complex expression there is an important difference. Where the prefix variation is used, the increment or decrement operation is applied before the value of the variable is applied to the rest of the calculation. Where the postfix version is used, the original value of the variable is used.

int a;
int b;

// Prefix. a is incremented before its value is assigned to b
a = 10;
b = ++a; //a = 11, b = 11;

// Postfix. a is incremented after its value is assigned to b
a = 10;
Operator Precedence:

All of the operators discussed in this article may be used together in a single expression. The result of the expression is dependant upon the order in which the individual operators are applied. This order is determined by the operator precedence, which applies an importance to each operator.

Over the next few articles we will build a table of the operator precedence for the most important C# operators. For the operators described so far, the order of precedence is as follows:

Increment / Decrement Operators:

++(postfix) --(postfix) ++(prefix) --(prefix)

Basic Arithmetic Operators:

* / % + -

It is important to understand the effect of the operator precedence table. The following code gives examples of how the importance of an operator affects the end result of an expression:

int a = 10;
int b = 6;
int c = 2;
int result;

// * is applied before +
result = a + b * c; //result = 22

// / is applied before -
result = a - b / c; //result = 7

// Order of precedence is *, /, +, -
result = a * b + b / c - 1; //result = 62
Parentheses Operator:

The parentheses operator allows modification of the order of precedence for operators. By surrounding parts of an expression with parentheses, the precedence of this part of the expression is increased to be of higher importance than items outside of the parentheses. The parentheses may also be nested. The order in which the operators are applied in the previous examples can therefore be modified.

int a = 10;
int b = 6;
int c = 2;
int result;

result = (a + b) * c; //result = 32

result = (a - b) / c; //result = 2

result = a * (b + b / (c - 1)); //result = 120

Friday, March 26, 2010

Chapter 3 :- Operators and Programming Constructs

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 ( <> )
{
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:-

Console.WriteLine("Enter your age:");
int Age = Convert.ToInt32(Console.ReadLine());
if (Age
{
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:-

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 < 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 <> 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:-

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 (<>)
{
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:-

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.

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(<>;<>;<>)
{
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.

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(<>)
{
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.

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.

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.

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);

Compiling and Execute your first C# Program

When I first heard about Microsoft's newest language, C#, my mouth started watering. For the audience with which I mostly deal (beginner programmers trying to break into the business) I thought C# would be the great equalizer---after all, everyone (experienced programmers as well as beginners) would be learning it at the same time.

Many of you may know I'm in the process of writing a C# book--this article will detail how to install it, and how to write your first program. For more, you'll need to read my book!


Installing C#:


To install C#, for the moment anyway, you don't need to purchase a thing. You just need to get your hands on the Microsoft .Net Framework.

C# is a language that comes with the Microsoft .Net (pronounced DOT-NET) Framework. The .Net Framework is an environment that permits .Net programs to run. C# is just one of many programming languages supported by the .Net framework (it even includes COBOL). Something tells me it will eventually become the most important.

The .Net Framework is not an Operating System---it's more like a shell that runs within Windows. For now, the .Net Framework is available only as a Beta version (currently Beta2). That means it hasn't been released for sale. Beta versions can be flaky, and if you read the fine print at the Microsoft Website, they'll tell you NOT to install the .Net Framework on a production PC. If this warning scares you, wait until the .Net Framework production version is ready (most likely, you'll have to pay for it, although at this point no one is sure how much).

The .Net Framework can be installed on a PC running Windows XP, Windows 2000 and Windows NT (sorry, Windows 98 and Windows ME users can't install the .Net Framework, and therefore can't install C#). In addition, you'll need to have Internet Explorer 5.01 or later installed, plus MDAC 2.6 (Microsoft Data Access Components)


Get the .Net Framework Software Developers Kit (SDK):


Right now, you can pick up the .Net Framework SDK from a variety of sources. I've received three in the mail for begin a registered of Visuowner al Basic 6, and I believe I've also seen CD's included in the Visual Basic Programmers Journal. At any rate, you can access this site

http://msdn.microsoft.com/downloads/default.asp?URL=/code/sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml

to download it. I should warn you the SDK is 123 Megabytes. You can download it all at once, in pieces, or get it from me if you take part in the C# class I'm offering in early 2002.


Install the .Net Framework SDK:

Once you have downloaded the SDK (install it in a folder of its own), double click on its Setup.exe program, and you should see a prompt similar to this one (if you don't have Internet Explorer 5.01 or higher installed, or MDAC 2.6, you will see different prompts).

If you have the CD, you'll see this screenshot when you insert the CD-ROM. Otherwise, you'll see the screenshot that asks you if you wish to install the .Net Framework SDK (two down…)

You don't want to install all of Visual Studio.Net--just the .Net Framework SDK, which is the part that contains the C# compiler (among other things). If you have the CD, click on 'Install only .NET Framework SDK'…

This is the window you'll see next. If you downloaded the SDK from the Microsoft Website, double clicking on the Setup.exe program will result in this window being displayed also. Answer 'Yes' to begin with the installation.

You should see files being copied and installed.

Fairly quickly, you should see this message. Answer 'yes'.

After answering 'Yes', you should see this window.

On my PC, I had MDAC 2.6 already installed, but the setup program suggested MDAC 2.7, and also Microsoft Internet Information Server. For the purpose of learning C#, you can click on Ignore.

This is the window you should see next. Click on Next to continue the installation.

Be sure to read the license agreement--click on the button indicating you accept the agreement, then click on the Next button to continue the installation.

This is the default installation selection. You need the Software Development Kit, and I highly recommend that you install the SDK Samples as well. Click on the Next button to continue the installation.

I suggest that you accept the Destination Folder--although if you are short on space on 'C', you may want to install to another drive if you have space there. Make certain that the 'Register Environment Variables' checkbox is selected--otherwise, when you try to compile your first C# program, Windows won't be able to find the compiler!

You should now see this window indicating that Components are being installed. On my PC, the Component installation took about ten minutes.

That's it--you'll receive this message indicating that the Installation is complete…

As is typical, you'll need to restart to finalize the installation. Click the 'Yes' button to restart.

Write your first C# program

After having successfully installed the .NET Framework SDK, among other things, the C# compiler will be installed somewhere in a folder on your PC. Provided you told the Installation program to update your Environmental variables, the location of the compiler should be registered properly on your PC, and you won't have to jump through any hoops to get the compiler to work.

Writing your first C# program is easy--start up Notepad and enter the following code…

class ILoveCSharp {
public static void Main(string[] args) {
System.Console.WriteLine("I love C#!");
}
}

Now save the program as "ILoveCSharp.cs" ( I recommend saving all of your C# programs in a folder called C#Files)

Compile your first C# program

Compiling your program is easy---but we will need to run the compiler from a Command Prompt. To do so, click on the Start-Run button and enter

command.com

in the Open Textbox…

After you click on the OK button, you will see this window…

which is the Command Prompt window. Type

cd \C#Files

to make your C#Files folder your current directory…

If you enter

dir

in the Command Prompt Window, you should see the C# program you just saved using Notepad.

Now it's time to compile your program using the C# compiler, csc. Enter

csc ILoveCSharp.cs

at the command prompt…

You should see a message that the compiler is executing. The absence of any error messages is great news--use the 'Dir' command to verify that your C# source file has been compiled into an executable…

Execute your first C# program

Executing your program is easy--just enter the name of your executable at the Command Prompt…

ILoveCSharp

You should see the phrase 'I love C#!' appear in the window.

Friday, March 19, 2010

Classes in c#:

consider the following code example,which desines a class:


plublic class hello
{

public static void main(string[] args)

{

system.concole.writeline("hello, world! \n");

}

}



the precending class declaration provides a method main() that will display the message "hello, world!" on your screen. The parts of the preceding code need the be examined.


The Main() Function



The first line of code that a C# compiler looks for in the source fle compiles is the mail() function is the entry point of the application.

The main() funtion is ideally used to create objects and invoke member functions.



The class keyword



The class keyword is used to declare a class. keywords are reserved words that have a special meaning. Here, the class keyword defines the class Hello. the braces, knon as delimiters, are used to indicate the start and end of class body.


Example:

Class Hello
{
....
}



The class Name

The class keyword is followed by the name of the class. in the preceding example, hello is the name of the class defined by using the class keyword. When you create classes, you must consider the following naming convention and rules.


Class Naming Conventions in C#


class names should follow certain naming conventions or guidelines. A class name:

* should be meaningful(strongly recommended).
* should ideally be a noun.
* can use ethire the pascal case or camel case. in pascal case the first letter is capitalized, such as myclass.



The Escape Characters

To display special characters such as the New line character or the backspace character,
you need to use escape characters.

The following table list the escape characters used in C#.



Escape sequence character name

\' single quotation mark
\>> double quotation mark
\\ Backslash
\0 NULL
\a Alert
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t horizontal tab
\v vertical tab

Thursday, March 11, 2010

Data Types in c#

C# provides various built-in data types. Built-n data types are the predefined data types.

The Following table lists some of the built-in data types.

Predefined type #Bytes Range of values

char 2 0 and 65535

Int 4 -2,147,483,648 and 2,147,483,647
foat 4 -3.402823e+38 and -1.401298e-45(for negative values)
1.401298e-45 and 3.402823e+38(for positive values)






predefined types #bytes Range of values


Double 8 -1.79769313486232e308
4.94065645841247e-324

(for negative values)

bool 1 True or False

String Variable length 0-2 billion unicode characters


Built-in data types are represented at the machine level. the storage requirment,
therefore,depends on the hardware. the #bytes column in the preceding table depicts
the bytes required to store the value in the memory.

Declaring and Initializing Variables

You can declare and initialize variables by using the following syntax:

=;

In the preceding syntax, the represents the kind of data type that will be stored in a variable and specifies the vlue that needs to be stored in avariable

Consider the following statement of variable declarations:

int age;

The preceding statement declares the variable choice of the char data type and initlizes the variable with the value y.

The data type represents the kind of data that will be stored in a variable