Home

Introduction to Values of a Program

   

Variables

 

Introduction to Storage

A computer is an electronic device that is used to solve one specific problem or to perform an assignment. For example, a fitness machine (Proform.com, 2010) allows a person to get in shape. A digital camera (Amazon.com, 2010) is used to take pictures. A cell phone (TigerDirect.com, 2010) is used to make phone calls. An ultrasound machine (Philips, 2010) is a health care machine used to produce images from inside a human body. A music synthesizer (Musician's Friend, 2010) can be used to create music:

Computer

Music Device

 

Cell Phone

Music Device

 

Music Device

 

An electronic device can also be used to solve general types of problems. For example, a personal computer (PC) can be used to perform calculations, word processing, or to store a database, etc.

In order to perform its assignment(s), a computer must receive values. This can be done by a person typing from a keyboard (cell phone, health care machine, PC, etc). Another machine would allow a user to only select from a preset number of keys (fitness machine, airplane, car, digital camera, microwave oven, refrigerator, etc). A person can also be asked to click something using the mouse. A person can also be asked to press some objects on a touch screen. In some cases, the values can come electronically (internally) from other sources (car, projector, etc). A computer can also get its values from a  combination of sources:

 

Information

To manage these different connections, a computer uses a flat object called a motherboard. Many parts are connected to this board. For example, there is a small machine whose main job is to perform calculations; it is called a processor, and it is connected to the motherboard. Then external objects are connected to the parts connected to the motherboard:

Information

The values a computer receives must be stored somewhere, called memory (like human memory). The computer uses two categories of storage (memory): temporary and permanent. We will come back to permanent storage in a later lesson (not because it is difficult but because we don't need it for now). The computer's temporary memory is used to hold information for a while and then lose it if that information is not needed anymore. For example, it can hold some values while the computer is turned on. If the computer gets turned off, the values stored in the temporary memory are lost. This is not an anomaly: that's the way it is designed (it would be catastrophic otherwise; try to imagine a computer that would keep everything; it would be filled in a short time and blow up :)).

The memory area where the computer temporarily stores some values is called random access memory or RAM:

Random Access Memory

Let's illustrate memory as a small cake pan made of boxes or holes that can contain something:

Variable Representation

We must mention, and keep in mind, that memory is larger than that and is made of millions of these hole-like objects.

As a programmer, your most regular job will consist of asking the compiler to temporarily store one or more values in the RAM. Without considering its small physical size, you should know that the RAM is huge, and you are not the only one using it. In fact, your program will not be the only one that uses the computer. For example, when the computer starts, it launches a program named an operating system (OS). Other programs (and utilities) also come to occupy the RAM.

To be able to manage the frequent requests of memory of your application, when you start a program, the compiler reserves a certain area of memory:

Reserved Memory

Because many programs use the RAM, if/when you want to store a value in it, you must provide some pieces of information. You must indicate the amount or memory you need and you must create a name that would be used to refer to that area of memory. The combination of these two pieces of information is called a variable.

ApplicationApplication: Introducing Variables

  1. Start Microsoft Visual C# 2010 Express or Microsoft Visual Studio 2010
     
    Author Note From now on, we will only refer to Microsoft Visual C#
  2. To create a new application, on the Start Page, click New Project...
  3. In the middle list, click Empty Project
  4. Change the Name to gdcs2 (which stands for Georgetown Dry Cleaning Services 2)
  5. Click OK
  6. To create a file for the code, on the main menu, click Project -> Add New Item...
  7. In the middle list, click Code File
  8. Change the Name to CleaningOrder
  9. Click Add
  10. In the empty document, type the following:
    class Order
    {
        static void Main()
        {
        	System.Console.WriteLine("Georgetown Dry Cleaning Services");
            System.Console.ReadKey();
        }
    }

Names

A variable must have a name and there are stricts rules you must follow to create a name. To start, there are words, called keywords, that you must not use because the language itself uses them. These keywords are:

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

There are other names that are not considered C#Keywords but should be avoided because they may cause a conflict in your code. They are referred to as contextual keywords and they are:

add global let partial (type) set where (generic)
dynamic group orderby remove value where (query)
from into partial (method) select var yield
get join        

As mentioned already, there are rules you must observe to name anything in your program. There are rules specified by the C# language standard but there are also rules you can add for your own taste. In our lessons, here are the rules we will follow to name things:

  • A name can consist of one letter (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, or z). Although these are letters of the US English alphabet, the C# language accepts international (non-US English) letters (that follow the Unicode standard)
  • The C# language allows that a name be made of an underscore only _. Although this is allowed, you should refrain from using the underscore as the only character of a name. It makes the code difficult to read
  • Except for the underscore, special symbols are not used anywhere in a name. Therefore, don't use |, !, ", /, $, %, ?, &, *, (, ), +, #, \, @, <, >, [, ], ;, {, }, or the comma inside any name
  • If the name is made of more than one character, it must start with either a letter or an underscore
  • After the first letter or underscore, the name can have a combination of letters, digits (0, 1, 2, 3, 4, 5, 6, 7, 8, or 9), and/or underscores
  • The name cannot have a space

Besides these rules, you can also create your own rules but that follow the above restrictions. For example:

  • It the name of a variable is in one word, many people use lowercase letters
  • If the name is a combination of words, many people use the camel notation in which the first word is in lowercase and the first letter of each subsequent word is in uppercase

C# is case-sensitive. This means that the names Case, case, and CASE are completely different. For example, main is always written Main.

Values and Variables on the Console

The applications of a C# language display their results in a dark object called the DOS window. Here is an example:

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

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

If you write System.Console.WriteLine() with empty parentheses, an empty line would be displayed.

Numeric Representations

 

Introduction

A computer program is a series of instructions that tell the computer what to do, when to do something, and how to do it. You, as the programmer, create these instructions. As mentioned in the previous lessons, you write the instructions in a text editor based on rules of the C# language but using a familiar language, which is English. An example of an instruction would ask the program to store a number in the computer memory. Another instruction could ask the computer to add a number to the previously stored number. Another instructor could ask the computer to move something from one part to another. The instructions you write must be transmitted to the computer.

As you can imagine, different people write various and all types of instructions. In fact, since C# is not the only computer language in the world, people use different means of giving instructions to the machine. To understand all of them and in fact to bring all these disparate instructions to one common language, the computer uses its own that all languages should understand and must follow. And actually, they don't. Instead, a computer language such as C#, that uses English, submits its instructions to an intermediary program named an assembler. The assembler transforms the previous instructions into a shorter version that uses new words but that are still in English. Using this new version, the assembler transforms the instructions in an even more simplified version (in reality, there is nothing simple with this process) that the computer can understand.

The simplified language the computer understands uses a combination of 1s and 0s. This means that the assembler must bring your C# instructions to 1s and 0s. The combinations or sequences of 1s and 0s indicate what needs to be done.

Numeric Systems

We are familiar with the system that uses 10 digits as 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. A combination of these 10 digits can produce any number we want. Because this system uses 10 digits. It is named the decimal system.

As mentioned already, the language of the computer is made of combinations of two values: 1 and 0. This is called the binary system (because it is based on two values only). Examples of numbers in the binary system, or binary numbers, are 1, 10, 1001, or 1010110111. When you submit a value to a computer, the value must be changed into a compbination of 1s and 0s.

You can imagine how hard it would be to represent a large number. One alternative uses the 10 digits of the decimal system and uses the first 6 letters of the English alphabets: A, B, C, E, D, and F or a, b, c, d, e, and f. This means that this system uses a combination of 16 characters to create any number. For this reason, it is called the hexadecimal system. To differenciate a hexadecimal number from a word, the number must start with 0x. Examples are 0x2, or 0xED8, or 0x962AAED3.

Signed and Unsigned

One of the characteristics of a number is to indicate whether it is lower than 0, equal to 0, or higher than 0. A number that is lower than 0 is said to be negative. Such a number must be preceded by -. If a number is higher than 0, it is said to be positive. Such a number can be preceded by + or no sign. The ability for a number to hold a sign makes it possible to say that such a number is signed. It is important to know that, when a number is said to be signed, that number can be negative or positive.

Any number that uses neither - or + is said to be positive and, because it doesn't use a sign, it is said to be unsigned. Normally, the 0 number doesn't use a sign.

Variable Declaration

 

Representing Memory Bits

We mentioned that, to store a value in the computer memory, you must indicate how much memory you will need and you must give it a name. The amount of memory you need is referred to as a data type. As you can imagine, different values require different amount of memory. We also mentioned that the computer considers a value as a combination of 1s and 0s. The area of memory that holds a single piece of 1 or 0 is called a bit.

Consider a bit like a small object (like a cup of a cup cake) that can be full or can be empty:

Variable Representation

When it is empty, a bit holds a value or 0. When it is full, it holds a value of 1:

Variable Representation

Different combinations of empty (0) and full (1) objects produce the necessary values.

Declaring a Variable

To use a combination of bits, you let the compiler know that you want a variable. This is referred to as declaring a variable. As mentioned already, the amount of memory you need is called a data type. Therefore, when declaring a variable, you must specify the desired data type. In C# (and many other languages, but not all languages), a data type is represented by a keyword (in some languages such as C and C++, a data type can be specified using a combination of keywords).

To actually declare a variable, you have two options.

  • If you know the type of value you want to store in memory, use the following formula:
    DataType VariableName;
    In later sections, we will seen what data types are available
  • If you don't want to specify the type of value, you have other options
    • You can use the var keyword
    • You can use the object keyword
    • You can use the dynamic keyword

Initializing a Variable

 

The Nullity of a Variable

When you declare a variable, you ask the compiler to reserve a certain area and amount of memory to eventually hold a value for that variable. At that time, no clear value is stored in that reserved area of memory (some languages, such as Visual Basic, put an initial value in that area, depending on the type of value you specified). Instead, the area gets filled with garbage (with some languages, such as C/C++, you can find out what that garbage is; some other languages, such as C#, don't allow you to access that garbage; after all, it is garbage and it is useless). A value is referred to as null when it cannot be clearly determined. A null value is not 0 because 0 is a an actual value.

In C#, normally, not all variables can hold null values. When declaring a variable, to indicate that it can hold either an actual value or it can be null, after its data type, add the question mark. This can be done as follows:

DataType? VariableName;

Assigning a Value to a Variable

Initializing a variable consists of storing an initial value in that reserved area. The technique you use is the same for all types but the type of value you want to store depends: you should not and must not try to store just any type of value.

To assign a value to a variable:

  • Type its data type, followed by a name for the variable, followed by =, followed by the desired but appropriate value. This can be done as follows:
    class Exercise
    {
        static void Main()
        {
    	DataType VariableName = DesiredValue;
        }
    }
    If you use this approach, you can first declare the variable by specifing its name and its data type ended by a semicolon. Then, on another line, type the name of the variable, followed by =, and the value. This can be done as follows:
    class Exercise
    {
        static void Main()
        {
    	DataType VariableName;
    
    	VariableName = DesiredValue;
        }
    }
  • Type the keyword var followed by the variable's name, followed by =, and followed by the value. This can be done as follows:
    class Exercise
    {
        static void Main()
        {
    	var VariableName = DesiredValue;
        }
    }
    This time, you must do this at once: you cannot first declare the variable on one line using the var keyword and ending with a semicolon, then initialize the variable on another line. You would receive an error. The following formula will not work:
    class Exercise
    {
        static void Main()
        {
    	var VariableName;
    	
    	VariableName = DesiredValue; // Error
        }
    }
  • Two other options consist of using the object or the dynamic keywords

When you declare a variable and initialize it, the compiler stores its value in the memory that was reserved for it. You can then access that value when you want. And of course, you can change it if necessary.

The null Value

As mentioned already, when declaring a variable, you can indicate that it can hold a null value by adding a question mark to its data type. To let you initialize the variable, the C# language provides the null keyword. To initialize a variable with it, simply assign null to it:

  • You can assign null when declaring the variable:
    class Exercise
    {
        static void Main()
        {
    	DataType? VariableName = null;
    	
    	// You can use the variable
        }
    }
  • You can assign null after the variable has been declared:
    class Exercise
    {
        static void Main()
        {
    	DataType? VariableName;
    	
    	VariableName = null;
    	
    	// You can use the variable
        }
    }

The rule is that you must assign the value before the variable can be used.

A Byte

 

A Combination of Four Bits

Although there are cases where you can use or access a bit, you cannot actually store a value in it. That is, you cannot ask the compiler to store the value 1 is a certain bit. This is because even the simplest value in C# needs more than one bit to store itself. Still, the minimum combination of bits you can be concerned with is four (in some languages, or in some implementations of the Assembly language, a combination of four bits is called a nibble).

By creating different combinations of empty (0) and full (1) objects grouped in four, you can get 16 combinations:

Combinations of Four Bits Combinations of Four Bits
Combinations of Four Bits Combinations of Four Bits

 

 

In a combination of four bits, the bits are counted as 0, 1, 2, and 3. The bit on the most right side is Bit 0 and it is called the low order bit (or LOBIT):

Four Bits

The last bit, the bit on the most left side, is Bit 3 and it is called the high order bit (or HIBIT).

If you represent the four-combination bits in binary formats, you get 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111, which produces 16 combinations. In decimal format, these combinations produce 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. In hexadecimal format, these combinations produce 0x0 (0x0000), 0x1 (or 0x0001), 0x2 (or 0x0002), 0x3 (or 0x0003), 0x4 (or 0x0004), 0x5 (0x0005), 0x6 (0x0006), 0x7 (or 0x0007), 0x8 (or 0x0008), 0x9 (or 0x0009), 0xA (or 0xa), 0xB (or 0xb), 0xC (or 0xc), 0xD (or 0xd), 0xE (or 0xe), and 0xF (or 0xF).

As a result, we get a table as follows:

Decimal Binary Hexadecimal
0 0000 0x0
1 0001 0x1
2 0010 0x2
3 0011 0x3
4 0100 0x4
5 0101 0x5
6 0110 0x6
7 0111 0x7
8 1000 0x8
9 1001 0x9
10 1010 0xA
11 1011 0xB
12 1100 0xC
13 1101 0xD
14 1110 0xE
15 1111 0xF

Table of Numeric Conversions

The minimum and maximum values in a combination of four bits are:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 15 0xf 1111

You will never be concerned with combinations of four bits because you cannot store anything in it (these combinations are too small). We presented them here for two reasons. First, you should be aware of such a thing as a combination of four bits so you will know where the number 16 comes from when you see it mentioned in different places. Second, it allowed us the introduce the byte.

A Combination of 8 Bits

A byte is a combination of eight adjacent bits. The first bit, located on the most right side, is Bit 0. The last bit, on the most left side, is Bit 7:

Byte Representation

Bit 0 is called the least significant bit. It is also valled the low order bit or LOBIT. Bit 7 is called the most significant bit. It is also called the high order bit or HIBIT.

If you create different combinations of empty (0) and full (1) objects grouped in eight, in binary formats, you get 00000000, 00000001, 00000010, 00000011, 00000100, 00000101, 00000110, 00000111, 00001000, 00001001, 00001010, 00001011, 00001100, 00001101, 00001110, 00001111, etc, up to 11111111. When a large number is represented in binary format, it can be difficult to read. An alternative is to create groups of four bits so that instead of writing 01001011, you would write 0100 1011.

To evaluate the number of combinations in decimal format, you use the number 2 that represents decimal, you elevate it to the power of the position of the bit (0, 1, 2, 3, 4, 5, 6, or 7), and you add the number. This can be done as follows:

27 + 26 + 25 + 24 + 23 + 22 + 21 + 20
= 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1
= 255

Therefore, we 255 possible combinations of eight bits. The combinations can also be represented in hexadecimal format as 0x1, 0x2, ..., 0xA, 0xA1, ..., 0xC8, ..., up to 0xFFFF

In the three numeric systems, we get:

Decimal Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

The minimum storage area offered by the (Intel) computer is the byte. As you know already, a byte is a group of 8 consecutive bits. The amount of memory space offered by a byte can be used to store just a single symbol, such as those you see on your keyboard. These symbols, also called characters, have been organized by the American Standard Code for Information Exchange (ASCII) in a set list. But, ASCII uses only 128 decimal numbers (based on a 7-bit format) to represent symbols counted from 0 to 127. To compensate for the remaining 1 bit, IBM used it to organize special characters, foreign language characters, mathematical symbols, small graphics, etc. Each one of these characters has a decimal, a hexadecimal, and a binary equivalents.

Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can pass it to Write() or WriteLine() and include the character between single-quotes, as follows:

class Exercise
{
    static void Main()
    {
	System.Console.WriteLine('n');
    }
}

Code

The file was saved as Exercise.cs in a folder named Variables on the C:\ drive. When compiled and executed, it displayed the letter n

Variable

Characters

In the English alphabet, a letter 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:

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

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

This would produce:

Variable

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

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

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

This would produce:

Student Gender: M
Note
All C-based languages support the char data type

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".

Note:
All C-based languages support these escape sequencces

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.

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:

Note:
C and C++ don't have a byte data type
byte Age;

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

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

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

This would produce:

Byte

Make sure you don't 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:

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

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

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:

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

        System.Console.Write("Number: ");
        System.Console.WriteLine(number);
	System.Console.ReadKey();
    }
}

This would produce:

Number: 254
Press any key to continue . . .

ApplicationApplication: Using Bytes

  1. Change the Program.cs file as follows: 
    class Order
    {
        static void Main()
        {
            byte? shirts = null;
            byte? pants  = null;
    
            shirts = 4;
            pants  = 1;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("========================");
            System.Console.WriteLine("Item Type  Qty");
            System.Console.WriteLine("------------------------");
            System.Console.Write("Shirts      ");
            System.Console.WriteLine(shirts);
            System.Console.Write("Pants       ");
            System.Console.WriteLine(pants);
            System.Console.WriteLine("========================");
            
            System.Console.ReadKey();
        }
    }
  2. To execute the application, on the main menu, click Debug -> Start Debugging. This would produce: 
    -/- Georgetown Cleaning Services -/-
    ========================
    Item Type  Qty
    ------------------------
    Shirts      4
    Pants       1
    ========================
  3. To close the DOS window, press Enter

Signed Byte

A byte number is referred to as signed if it can hold a negative or 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:

class Exercise
{
    static void Main()
    {
	sbyte roomTemperature = -88;

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

This would produce:

When we entered, the room temperature was -88

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
 

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 et 32767. Here is an example:

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

        System.Console.Write("School Effective: ");
        System.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:

Note:
C++ supports the signed and the signed short data types.
class Exercise
{
    static void Main()
    {
	short numberOfPages;
	short temperature;

	numberOfPages = 842;
	temperature   = -1544;

	System.Console.Write("Number of Pages of the book: ");
	System.Console.WriteLine(numberOfPages);
	System.Console.Write("Temperature to reach during the experiment: ");
	System.Console.Write(temperature);
	System.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.

Unsigned Short Integers

If a variable must hold positive and relatively small numbers, it is referred as an unsigned short integer. Such a variable can be declared using either the var or the ushort keyword. An unsigned short integer can hold numbers that range from 0 to 65535 and therefore can fit in 16 bits. Here are examples:

Note:
the C++ equivalent is unsigned short.
class Exercise
{
    static void Main()
    {
	// These variables must hold only positive integers
	ushort numberOfTracks;
	ushort musicCategory;

	numberOfTracks = 16;
	musicCategory  = 2;

	System.Console.Write("This music album contains ");
	System.Console.Write(numberOfTracks);
	System.Console.WriteLine(" tracks");
	System.Console.Write("Music Category: ");
	System.Console.Write(musicCategory);
	System.Console.WriteLine();
    }
}

This would produce:

This music album contains 16 tracks
Music Category: 2

ApplicationApplication: Using Unsigned Short Integers

  1. To use unsigned short integers, change the file as follows: 
    class Order
    {
        static void Main()
        {
            byte? shirts = null;
            byte? pants  = null;
            ushort? otherItems = null;
    
            shirts     = 4;
            pants      = 1;
            otherItems = 3;
    
            System.Console.WriteLine("-/- Georgetown Cleaning Services -/-");
            System.Console.WriteLine("========================");
            System.Console.WriteLine("Item Type  Qty");
            System.Console.WriteLine("------------------------");
            System.Console.Write("Shirts      ");
            System.Console.WriteLine(shirts);
            System.Console.Write("Pants       ");
            System.Console.WriteLine(pants);
            System.Console.Write("Other Items ");
            System.Console.WriteLine(otherItems);
            System.Console.WriteLine("========================");
            
            System.Console.ReadKey();
        }  
    }
  2. To execute the program, on the main menu, click Debug -> Start Debugging. This would produce: 
    -/- Georgetown Cleaning Services -/-
    ========================
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty
    ------------------------
    Shirts      4
    Pants       1
    Other Items 3
    ========================
  3. To close the DOS window, press Enter
  4. Close your programming environment
  5. When asked whether you want to save, click No

 

References

Amazon.com. (2010). Canon Digital Rebel XSi 12.2 MP Digital SLR Camera with EF-S 18-55mm f/3.5-5.6 IS Lens (Black). Retrieved May 22, 2010, from http://www.amazon.com/Canon-Digital-Camera-18-55mm-3-5-5-6/dp/B0012YA85A/ref=sr_1_3?ie=UTF8&s=photo&qid=1274533087&sr=1-3
Musician's Friend. (2010). Musician's Friend | Your Online Music Equipment & Pro Audio Store | Best Prices, Great Service. Retrieved May 22, 2010, from http://www.musiciansfriend.com/
Philips. (2010). HD11 XE Ultrasound System. Retrieved May 22, 2010, from http://www.healthcare.philips.com/us_en/products/ultrasound/systems/hd11xe/index.wpd
PRO-FORM. (2010). Exercise Equipment at Proform.com. Retrieved May 22, 2010, from http://www.proform.com/
TigerDirect.com. (2010). Motorola F3 Unlocked GSM Cell Phone - Black. Retrieved May 22, 2010, from http://www.tigerdirect.com/applications/SearchTools/item-details.asp?EdpNo=5394928&Sku=M151-2556
 
 

Previous Copyright © 2010-2016, FunctionX Next