Home

Introduction to Variables

 

Variables

 

Definition

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 LearningPractical 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
  3. In the Templates section, click Console Application
  4. 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:

Besides these keywords, C# has other words that should be reserved only depending on how and where they are used. These are referred to as contextual keywords and they are:

Once you avoid these words, there are rules you must follow when naming your objects. On this site, here are the rules we will follow:

  • The name must start with a letter or an underscore
  • After the first letter or underscore, the name can have letters, digits, and/or underscores
  • The name must not have any special characters other than the underscore
  • The name cannot have a space

Besides these rules, you can also create your own but that abide by the above.

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

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

The Numeric Systems

 

Introduction

When a computer boots, it “loads” the operating system. If you want to use a program, you must find it either on the Start menu or from its directory and take the necessary action to open it. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who want to interact with the machine.

To write your programs, you will be using alphabetic letters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, 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, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use characters that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : “ < > ; ‘ , . /. Some of these symbols are used in the C# language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions.

Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After typing an instruction, the compiler would translate it to machine language. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in its memory using a certain amount of space for each instruction or each item you use.

There are three numeric systems that will be involved in your programs, with or without your intervention.

The Binary System

When dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system.

When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One.

The sequence of the symbols of the binary system depends on the number that needs to be represented.

The Decimal System

The numeric system that we are familiar with uses ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits.

When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion.

Decimal Values: 3849, 279, 917293, 39473
Non- Decimal Values: 0237, 0276382, k2783, R3273

The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (= 0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 101 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are:

2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751

67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048

Another way you can represent this is by using the following table:

etc Add 0 to the preceding value 1000000 100000 10000 1000 100 10 0

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s).

The Hexadecimal System

While the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the family of Latin languages consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. To produce a hexadecimal number, you use a combination of these sixteen symbols.

Examples of hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number?

Author Note From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase.

Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e
Non-Hex Numbers: 0686, ffekj, 87fe6y, 312

There is also the octal system but we will not use it anywhere in our applications.

Signed and Unsigned

The numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items.

In real life, there are numbers counted in decrement values. Such numbers start at –1 and move down to -2, -3, -4 etc. These numbers are qualified as negative.

When you write a number “normally”, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the – on the left side of the number. The – symbol is called a sign. Therefore, if the number does not have the – symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned.

Data Types

In order to use a variable in your program, the compiler must be aware of it. Once the compiler knows about a variable, it would reserve an amount of memory space for that variable

variable Representation

Using its name, you can refer to a particular variable when necessary. Because there are various types of variables a program can use, such as the employee's name, his home address, the desired salary, years of experience, education level, etc for our employment application analogy, the compiler needs a second piece of information for each variable you intend to use. This piece of information specifies the amount of space that a variable needs. You can see that, to store a character, such as an employee's gender (M or F) or an answer as Y or N to a question, the compiler would certainly not need the same amount of space to store the name of the last school attended by an employee.

A data type is an amount of space needed to store the information related to a particular variable.

The name of a variable allows you and the compiler to refer to a particular category of information in your program. The data type allows the compiler to reserve an adequate amount of memory space for a variable. Because you are the one who writes a program, you also tell the compiler the amount of memory space each particular variable will need. Based on this, the C# language provides categories of data types used to specify this amount of space needed for a variable.

As stated already, before using a variable, you must communicate your intentions to the compiler. Making the compiler aware is referred to as declaring the variable. To declare a variable, you have two options:

  • If you know the type of variable you want to use, you can provide it followed by the name of the variable. Based on this, one syntax used to declare a variable is:
     
    DataType VariableName;
  • As an alternative, you can provide only a name for the variable but let the compiler specify its data type. To declare such a variable, you use the var keyword followed by the name of the variable. This certainly would not be enough. For the compiler to know how much space is necessary, you must provide a value for the variable

Providing a value for a variable is referred to as initializing it. This can be done for declared with either a data type or the var keyword:

  • If you declare a variable using data type, the initialization could be optional (depending on how you will access the variable)
  • If you declare a variable using the var keyword, you must initialize it

To initialize a variable, on the right side of its name, type the assignment operation, which is =, followed by a value:

  • If you declare a variable using a data type, you must initialize it with an appropriate value. When we study the data type, we will see what value is appropriate for what data type
  • If you declare a variable using the var keyword, you can initialize it with almost any type of value (of course there are exceptions). The purpose of using the var keyword is to let the compiler decides what type the variable is. To make this decision, the compiler refers to the type of value the variable was assigned with.
Author Note For illustrative purposes, in many lessons, we will use the var keyword to declare variables. In practicality, don't abuse or overuse the var keyword. It can be confusing. The beauty of var, which is one of its rules, is that you MUST initialize its variable. This makes it possible to know the type of variable you are using. On the other hand, if you declare too many  variables with var and initialize them with the same types of values, you could get confused with the type of data that each of those variables is holding. So, use the var keyword sparingly: It can be a beauty but, if overused, it can be confusing. The good news is that the compiler knows exactly what it is doing and what it is asked to do.
 

Representing Numbers

 

A Bit

The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to represent its information. It represents data using only a 0 or 1 value:

Bit 0 Bit 1
0 1

You can represent a piece of information with one of two states. This technique of representing values is the same as the binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system.

Although the C# compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to manipulate the information stored in a bit.

The Four-Bit Combination

The single bit is used only to represent a tinny piece of information. To get effective numbers, the computer combines the bits. The first combination of bits consists of grouping four consecutive bits.

Bit 0 Bit 0 Bit 0 Bit 0

To count the bits, we number them starting at 0, followed by 1, 2, and 3. The count starts with the most right bit:

The first bit, on the right side of the group, is called the Low Order bit or LO bit. This is also called the least significant bit. The last bit, on the left side of the group, is called the High Order bit or HI bit; it is also called the most significant bit. The bit on the right side is counted as bit 0. The bit on the left side is counted as bit 3. The other bits are called by their positions: bit 1 and bit 2.

Once again, each bit can have one of two states. Continuing with our illustration, when a cup is empty, it receives a value of 0. Otherwise, it has a value of 1. On a group of four consecutive bits, we can have the following combinations:

This produces the following binary combinations: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 = 16 combinations. When using the decimal system, these combinations can be represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15.

This combination is also a system that the computer uses to count bits internally. Sometimes, in your program or in the help files, you will encounter a number that is less than four bits, such as 10 or 01 or 101. The technique used to complete and fill out the group of 4 bits consists of displaying 0 for each non-represented bit. The binary number 10 will be the same as 0010. The number 01 is the same as 0001. The number 101 is the same as 0101. This technique is valuable and allows you to always identify a binary number as a divider of 4.

When all bits of a group of 4 are 0, the combination has the lowest value, which is 0000. Any of the other combinations has at least one 0 bit, except for the last one. When all bits are 1, this provides the highest value possible for a group of 4 bits. The lowest value, also considered the minimum value, can be represented in the decimal system as 0. The highest value, also considered the maximum, can be expressed in decimal value as 24 (2 represents the fact that there are two possible states: 0 and 1; 4 represents the fact that there are four possible combinations), which is 16. This produces 16 because 24 = 16.

As you can see, the binary system can appear difficult to read when a value combines various bit representations. To make it easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:

Decimal Binary Hexadecimal
0 0000 0
1 0001 1
2 0010 2
3 0011 3
4 0100 4
5 0101 5
6 0110 6
7 0111 7
8 1000 8
9 1001 9
10 1010 A
11 1011 B
12 1100 C
13 1101 D
14 1110 E
15 1111 F

Table of Numeric Conversions

When looking at a binary value represented by 4 bits, you can get its decimal or hexadecimal values by referring to the table above. A group of four consecutive bits has a minimum and maximum values on each system as follows:

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

Although the C# compiler recognizes a group of four consecutive bits, you cannot store any variable in it. You can, however, manipulate the bits of the group.

A Byte

 

Introduction

A byte is a group or eight consecutive bits. The bits are counted from right to left starting at 0:

The most right bit is bit 0; it is called the least significant bit. It is also referred to as the Low Order bit, the LO bit, or LOBIT. The most left bit is bit 7; it is called the most significant bit. It is also referred to as the High Order bit, the HI bit, or HIBIT. The other bits are referred to following their positions:

The bits of a byte

Using the binary system, you can represent the byte using a combination of 0s and 1s. When all bits have a value of 0, the byte is represented as 00000000. On the other hand, when all bits have a value of 1, the byte is represented as 11111111. When the number grows very large, it becomes difficult to read. Therefore, you can represent bits in groups of four. Instead of writing 00000000, you can write 0000 0000. This makes the number easier to read.

If you have the patience to create combinations of bits using the boxes as we did for the group of 4, you would find out that there are 256 possible combinations. Another way to find it out is by using the base 2 technique:

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

Therefore, the maximum decimal value you can store in a byte is 255.

Remember that the byte with all bits having a value of 0 has its value set to 0. Since this byte also holds a valid value, the number of combinations = 255 + 1 = 256.

When a byte is completely represented with 0s, it provides the minimum value it can hold; this is 0000 0000, which is also 0. When all bits have a value of 1, which is 1111 1111, a byte holds its maximum value that we calculated as 255 in the decimal system. As done with the group of 4 bits, we get the following table:

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:

using System;

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

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

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.

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

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

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

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

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 of the ushort keyword. An unsigned short integer can hold numbers that range from 0 to 65535 and therefore can fit in 16 bits. Here is an example:

using System;

class NumericRepresentation
{
    static void Main()
    {
	// These variables must hold only positive integers
	ushort NumberOfTracks;
	ushort MusicCategory;

	NumberOfTracks = 16;
	MusicCategory  = 2;

	Console.Write("This music album contains ");
	Console.Write(NumberOfTracks);
	Console.WriteLine(" tracks");
	Console.Write("Music Category: ");
	Console.Write(MusicCategory);
	Console.WriteLine();
    }
}

This would produce:

This music album contains 16 tracks
Music Category: 2

Practical LearningPractical Learning: Using Unsigned Short Integers

  1. To use unsigned short integers, change the 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;
                ushort OtherItems;
    
                Shirts = 4;
                Pants = 1;
                OtherItems = 3;
    
                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.Write("Other Items ");
                Console.WriteLine(OtherItems);
                Console.WriteLine("========================");
                Console.WriteLine();
            }
        }
    }
  2. Execute the program. This would produce:
     
    -/- Georgetown Cleaning Services -/-
    ========================
    Order Date: 7/15/2002
    ------------------------
    Item Type  Qty
    ------------------------
    Shirts      4
    Pants       1
    Other Items 3
    ========================
    
    Press any key to continue . . .
  3. Close the DOS window

 

 

Previous Copyright © 2008-2011 FunctionX Next