Saturday, August 7, 2010

Short Integers

Short Integers


A word, which is a group of 16 contiguous bits or 2 bytes, can be used to hold a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. To declare a variable for such a value, you can use the var keyword and initialize the variable with a value between –32768 to 32767. Here is an example:

using System;

class Exercise
{
static void Main()
{
var SchoolEffective = 1400; // Number of Students

Console.Write("School Effective: ");
Console.WriteLine(SchoolEffective);
}
}

This would produce:

School Effective: 1400
Press any key to continue . . .

Since the byte is used for characters and very small numbers, whenever you plan to use a number in your program, the minimum representation you should use is a word.

A natural number is also called an integer. If you want to declare the variable using a data type, the smallest integer you can store in a word is declared with the short keyword. Because a short integer is signed by default, it can store a value that ranges from –32768 to 32767. Here is an example program that uses two short integers:

using System;

class Exercise
{
static void Main()
{
short NumberOfPages;
short Temperature;

NumberOfPages = 842;
Temperature = -1544;

Console.Write("Number of Pages of the book: ");
Console.WriteLine(NumberOfPages);
Console.Write("Temperature to reach during the experiment: ");
Console.Write(Temperature);
Console.WriteLine(" degrees\n");
}
}

This would produce:

Number of Pages of the book: 842
Temperature to reach during the experiment: -1544 degrees

Because a short integer handles numbers that are larger than the signed byte, any variable you can declare for a signed byte can also be declared for a short variable.

A Word

A Word


Introduction


A word is a group of 16 consecutive bits. The bits are counted from right to left starting at 0:

Considered as a group of 16 bits, the most right bit of a word, bit 0, is called the least significant bit or Low Order bit or LO bit or LOBIT. The most left bit, bit 15, is called the most significant bit or High Order bit or HI bit or HIBIT. The other bits are referred to using their positions: bit 1, bit 2, bit 3, etc.

Considering that a word is made of two bytes, the group of the right 8 bits is called the least significant byte or Low Order byte or LO byte or LOBYTE. The other group is called the most significant byte or High Order byte or HI byte or HIBYTE.

The representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits by 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The minimum decimal value of a word is 0. The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0.

The maximum binary value represented by a word is 1111 1111 1111 1111. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1:

1*215+1*214+1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20

= 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1

= 65535

To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F:

1111 1111 1111 1111
f f f f
= 0xffff
= 0xFFFF
= 0Xffff
= 0XFFFF

Signed Byte

Signed Byte


A byte number is referred to as signed if it can hold a negative of a positive value that ranges from -128 to 127, which can therefore fit in a byte. To declare a variable for that kind of value, use the sbyte keyword. Here is an example:

using System;

class NumericRepresentation
{
static void Main()
{
sbyte RoomTemperature = -88;

Console.Write("When we entered, the room temperature was ");
Console.WriteLine(RoomTemperature);
Console.WriteLine();
}
}

This would produce:

When we entered, the room temperature was -88

Practical LearningPractical Learning: Using Bytes




1. Change the Program.cs file as follows:


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

namespace GeorgetownCleaningServices2
{
class Program
{
static void Main(string[] args)
{
byte Shirts;
byte Pants;

Shirts = 4;
Pants = 1;

Console.WriteLine("-/- Georgetown Cleaning Services -/-");
Console.WriteLine("========================");
Console.WriteLine("Item Type Qty");
Console.WriteLine("------------------------");
Console.Write("Shirts ");
Console.WriteLine(Shirts);
Console.Write("Pants ");
Console.WriteLine(Pants);
Console.WriteLine("========================");
Console.WriteLine();
}
}
}

2. Execute the program. This would produce:


-/- Georgetown Cleaning Services -/-
========================
Item Type Qty
------------------------
Shirts 4
Pants 1
========================

3. Close the DOS window

The Byte Data Type

The Byte Data Type


A byte is an unsigned number whose value can range from 0 to 255 and therefore can be stored in one byte. You can use it when you know a variable would hold a relatively small value such as people's age, the number of children of one mother, etc. To declare a variable that would hold a small natural number, use the byte keyword. Here is an example:

byte Age;

You can initialize a byte variable when declaring it or afterwards. Here is an example that uses the byte data type:

using System;

class ObjectName
{
static void Main()
{
Byte Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}

Make sure you do not use a value that is higher than 255 for a byte variable, you would receive an error. When in doubt, or when you think that there is a possibility a variable would hold a bigger value, don't use the byte data type as it doesn't like exceeding the 255 value limit.

Alternatively, you can also use the var keyword to declare the variable and initialize it with a small number. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Age = 14;
Console.Write("Student Age: ");
Console.WriteLine(Age);

Age = 12;
Console.Write("Student Age: ");
Console.WriteLine(Age);
}
}

Instead of a decimal number, you can also initialize an integral variable with a hexadecimal value. When doing this, make sure the decimal equivalent is less than 255. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Number = 0xFE;

Console.Write("Number: ");
Console.WriteLine(Number);
}
}

This would produce:

Number: 254
Press any key to continue . . .

Escape Sequences

Escape Sequences


An escape sequence is a special character that displays non-visibly. For example, you can use this type of character to indicate the end of line, that is, to ask the program to continue on the next line. An escape sequence is represented by a backslash character, \, followed by another character or symbol. For example, the escape sequence that moves to the next line is \n.

An escape can be included in single-quotes as in '\n'. It can also be provided in double-quotes as "\n".

The C# language recognizes other escape sequences.

Escape Sequence Name Description
\a Bell (alert) Makes a sound from the computer
\b Backspace Takes the cursor back
\t Horizontal Tab Takes the cursor to the next tab stop
\n New line Takes the cursor to the beginning of the next line
\v Vertical Tab Performs a vertical tab
\f Form feed
\r Carriage return Causes a carriage return
\" Double Quote Displays a quotation mark (")
\' Apostrophe Displays an apostrophe (')
\? Question mark Displays a question mark
\\ Backslash Displays a backslash (\)
\0 Null Displays a null character


To use an escape sequence, you can also first declare a char variable and initialize it with the desired escape sequence in single-quotes.

Characters

Characters


In the English alphabet, a character is one of the following symbols: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, and Z. Besides these readable characters, the following symbols are called digits and they are used to represent numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. In addition, some symbols on the (US QWERTY) keyboard are also called characters or symbols. They are ` ~ ! @ # $ % ^ & * ( ) - _ = + [ { ] } \ | ; : ' < ? . / , > "

Besides the English language, other languages use other or additional characters that represent verbal or written expressions.

C# recognizes that everything that can be displayed as a symbol is called a character. To declare a variable whose value would be a character, you can use the var keyword and initialize the variable with a character in single-quotes. Here is an example:

using System;

class Exercise
{
static void Main()
{
var Gender = 'F';

Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}

Alternatively, you can use the char keyword. Here is an example:

using System;

class Exercise
{
static void Main()
{
char Gender = 'M';

Console.Write("Student Gender: ");
Console.WriteLine(Gender);
}
}

This would produce:

Student Gender: M

Values and Variables on the Console

Values and Variables on the Console


As mentioned already, the applications we will create display in a dark object called the DOS window. Here is an example showing some values:

To display a value in this window, you can enter it in the parentheses of the Console.Write() or Console.WriteLine(). Here are two examples:

using System;

class Program
{
static void Main()
{
Console.WriteLine(248);
Console.Write(1);
}
}

If you write Console.WriteLine() with empty parentheses, an empty line would be displayed. In future lessons, we will learn what the meanings of Console, Write(), and WriteLine().

Names in C#

Introduction to Variables




A computer
receives information from different applications in various forms. Sometimes a person types it using the keyboard. Sometimes the user clicks the mouse. Sometimes information comes from another, more complicated source. The idea is that the computer spends a great deal of its time with various pieces of information. Information provided to the computer through a program is called datum and the plural is data. Sometimes the word data is used both for singular and plural items.

Data used by the computer comes and goes regularly as this information changes. For this reason, such information is called a variable.

When the user enters data in a program, the computer receives it and must store it somewhere to eventually make it available to the program as needed. For a program used to process employment applications, the types of information a user would enter into the program are the name, the residence, the desired salary, years of experience, education level, etc. Because there can be so much information for the same program, you must specify to the computer what information you are referring to and when. To do this, each category of piece of information must have a name.

Practical Learning: Introducing Variables


  1. Start Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional
    Author Note From now on, we will only refer to Microsoft Visual C#
  2. To create a new application, on the Start Page, on the right side of Create, click Project

# In the Templates section, click Console Application
# Change the Name to GeorgetownCleaningServices2 and click OK

Names in C#


To name the variables of your program, you must follow strict rules. In fact, everything else in your program must have a name. C# uses a series of words, called keywords, for its internal use. This means that you must avoid naming your objects using one of these keywords. They are:


Adding a Project


  • Adding a Project


One of the most valuable features of Microsoft Visual Studio 2005 is that it allows you to work on more than one project without launching more than one instance of the studio. This means that you can add a project to another project you are working on and treat each as a separate entity.

Before adding one project to another, you must save, or you must have saved, the current project. To add a project, in the Solution Explorer, you can right-click the most top node (it starts with Solution) and position the mouse on Add:

If you have a project that was previously saved but you don't want to open a separate instance of Microsoft Visual Studio for it, you can click Existing Project... This would bring the Add Existing Project dialog box that allows you to select a project from a folder.

To add a new project, after right-clicking, you can click New Project... If you add a new project, and if you want to keep it for future references, you must save it. To save the new project, you can click the Save All button on the Standard toolbar. After saving the new project, a folder with its name would be created inside of the folder of the solution.

On the right side of the name of the solution in Solution, the number of its projects is specified in parentheses, as 1 project, or 2 projects, etc.

After adding a project, each would be represented by its own node in the Solution Explorer and in the Class View. Here is an example:

Also, a sub-folder for each project is created in the folder of the solution:

In the Solution, the name of one of the projects, if there is more than one, is in bold characters. This project is called the StartUp Project. If, on the main menu, you click Debug -> Start Without Debugging, the project in bold characters would be executed. If you want to change the start up project, you can right-click its node and click Set As StartUp Project.



Executing a Project

After creating a project and writing code, you may want to see the result. To do this, you must execute the application. This would create an executable that you can use on other computers and that you can distribute to other people.

To execute an application, on the main menu, you can click Debug -> Start Without Debugging. Instead of going through the main menu every time, you can add the Start Without Debugging button to a toolbar. To do this, you can right-click any toolbar and click Customize... In the Commands property page of the Customize dialog box, you can click Debug in the Categories click, then drag Start Without Debugging, and drop it on a toolbar. Here is an example:


After adding the button(s), you can click Close. The next time you want to execute an application, you can just click this button.

Practical Learning: Executing an Application


  1. To execute the application, on the main menu, click Debug -> Start Without Debugging
  2. After viewing the result in a DOS window, press Enter to close it

A Solution

A solution is used to coordinate the different aspects of an application that is being created. When you create a project, it represents one detail of the application you have in mind. Besides the code you are writing, you may want to add other items. Instead of one project, in the next sections, we will see that a solution can contain more than one project.

When creating a project, the solution holds the same name as the project. You can see their names in the Solution Explorer:



The solution and a project can have different names. While working on a project, to rename the solution, in the Solution Explorer, you can click the first node, which is the name of the solution starting with Solution. Then, in the Properties window, click (Name) and type the name of your choice:



This name is temporary, especially if you have not yet saved the project. If you want to permanently save a solution for later use, there are two techniques you can use.

If you start saving a project for the first time, it would bring the Save Project dialog box. By default, Microsoft Visual Studio selects your personal directory as the path to the solution. This is called the location. In the location, Microsoft Visual Studio creates a folder as the solution of the project. The solution must have, or must be stored, in its own folder. As mentioned earlier, Microsoft Visual Studio uses the name of the project as the name of the solution. To rename the solution, you can change the string in the Solution Name text box. Remember that you can enter the name of the project in the Name text box. Here is an example:



When you save a project (for the first time), by default, Microsoft Visual C# creates a new folder for it in the My Documents\Visual Studio 2008\Projects folder. It uses the name of the solution to name the folder. It creates some files and stores them in that new folder. Then, it creates a sub-folder, using the name of the project, inside of the folder of the solution. Besides the sub-folder with the name as the project, it creates another folder named debug. It also creates another folder named Debug in the sub-folder of the name of the project. In each folder and some other folders, it creates some files that we will not pay attention to for now.

If the project had already been saved but you want to change the name of the solution, on the main menu, you can click File -> Save solution-name.sln As... This would bring the Save File As dialog box where you can specify the name of the solution and click Save.

Solution and Project Management

A Project

We have seen how to create a console application. Microsoft Visual C# allows you to create various other types of applications. This is why you should first display the New Project dialog box to select your option. Besides console applications, in future lessons, we will start some applications with the Empty Project. We will also learn how to create a library using the Class Library option. We will ignore the other three options in this book.

To control the indentation of your code, on the main menu, click Tools -> Options... In the left list, expand C#, followed by Formatting and click Indentation. Then change the options on the right side:




Saving a Project

In previous versions of Microsoft Visual C# (namely 2002 and 2003), you always had to formally create a project in order to use one and you always had to save it. After realizing that many of the projects that developers
or students create are for experimental purposes, Microsoft provided the ability to only temporarily create a project, then to save it or not. Saving a project allows you to keep on a medium so you can refer to it later.

When Microsoft Visual Studio 2008 (any edition) is installed, it creates a folder named Visual Studio 2008 in your My Documents folder. The My Documents folder is called your personal drive or your personal directory. Inside of the Visual Studio 2008 folder, it creates a sub-folder named Projects. By default, this is where it would save your projects, each with its own folder.

To save a project, on the Standard toolbar, you can click the Save All button . Alternatively, on the main menu, you can click File -> Save All. If the project had already been saved but you want to save it under a different name, on the main menu, you can click File -> Save project name As...

Code Colors

Code is written in a wide area with a white background. This is the area you use the keyboard to insert code with common readable characters. The Code Editor uses some colors to differentiate categories of words or lines of text. The colors used are highly customizable. To change the colors, on the main menu, you can click Tools -> Options... In the Options dialog box, in the Environment section, click Fonts and Colors. To set the color of a category, in the Display Items section, click the category. In the Item Foreground combo box, select the desired color. If you want the words of the category to have a colored background, click the arrow of the Item Background combo box and select one:


Code Colors

Comments

A comment is a line or paragraph of text that will not be considered as part of your code of a program. There are two types of comments recognized by C#.

To display a comment on a line of text, start the line with two forward slashes //. Anything on the right side of // would be ignored. Here is an example:

// This line will be ignored. I can write in it anything I want

The above type of comment is used on only one line. You can also start a comment with /*. This type of comment ends with */. Anything between this combination of /* and */ would not be read. Therefore, you can use this technique to span a comment on more than one line.

Console Applications

The C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window. Those are the types of applications we will create in our lessons.

To study the C# language, we will use Microsoft Visual C# 2008 Express Edition or Microsoft Visual C# 2008 Professional. To get Microsoft Visual C# 2008 Express Edition, you can download it free from the Microsoft web site. After downloading it, you can install it.

To launch Microsoft Visual C# 2008 Express Edition, you can click Start -> (All) Programs -> Microsoft Visual C# 2008 Expression Edition:


To launch Microsoft Visual C# 2008 Professional, you can click Start -> (All) Programs -> Microsoft Visual Studio 2008. To create the type of applications we will study in our lessons, on the main menu, you can click File -> New Project... In the Templates section of the New Project dialog box, you can click Console Application, accept the default name or change it:




After clicking OK, a skeleton code would be created for you. Right now, we will not review every part of the code. Everything will be introduced and explained as we move on.

C#'s Data Type

C# contains two general categories of built-in data types:
1. value types
2. reference types.

C# has the following reserved keywords:

abstract as base bool break

byte case catch char checked

class const continue decimal default

delegate do double else enum

event explicit extern false finally

fixed float for foreach goto

if Implicit In Int Interface

Internal Is lock long namespace

new null object operator out

override params private protected public

readonly ref return sbyte sealed

short sizeof stackalloc static string

struct switch this throw true

try typeof uint ulong unchecked

unsafe ushort using virtual void

volatile while

The C# Keywords

abstract as base bool break
Byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using virtual volatile

To create and run programs using the C# command-line compiler:

1. Enter the program using a text editor.
2. Compile the program.
3. Run the program.

Compiling the Program

C:\>csc Example.cs

Prior to running csc.exe, you may need to run the batch file vcvars32.bat, which is typically found in the //Program Files/Microsoft Visual Studio.NET/Vc7/Bin directory.

1. The name of a C# program is arbitrary
2. By convention, C# programs use the .cs file extension