Variables and Data Types |
|
Your programs will mainly allow the user of your application to interact with the computer. During this interaction, the user will deal with two categories of information: information that is already in the computer and information supplied by the user. Information that is already in the computer will come from various sources; some of that is from the pieces of hardware that compose the user’s machine, some of that is from the computer (the operating system and other applications that are running on the same computer), and some will have been created by you as part of your application. When interacting with the computer, the user will enter information mainly using the keyboard and/or the mouse. Regardless of what information the user is using, the things used or needed by your program are stored or will be stored in the computer.
As an application developer, you will decide what types of information are necessary for your application and how these things would be used. When creating an application, you will provide these pieces of information to the computer, the computer then puts them together. When your program opens, part of your application gets “loaded†into the RAM. When the user is using your application, the information that your application requests also goes into the RAM while your application is processing such requests. Because your program will be made of many of these things, the computer needs to know what these things would be, and how much space each one of them would need. Because such a thing can change (vary) throughout your program, it is called a variable. Before using such a variable, you must first let the compiler know. Letting the compiler know about a variable is referred to “Declaring†the variable. The compiler will need two pieces of information concerning each variable: the amount of space the variable will need, and a name to recognize that variable. Therefore, the formula of declaring a variable is: SpaceOccupied VariableName;
When using the various necessary variables in your programs, you will need to identify each one of them. A variable is primarily recognized by its name. C++ provides rules for naming items in your program. The name of a variable:
A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth. The C++ compiler has a list of words reserved for its own use and you must not use any of these words to name your own objects or functions. The reserved words are:
Most compilers also have their own list of reserved words. Because this depends on the compiler, we cannot review all of them. Avoid starting the name of a variable with two underscores such as __finally or __stdcall. C++ is case-sensitive; this means that CASE, Case, case, and CaSe are four completely different words. To make your programming experience easier and personal, you can add your own rules to those above. Some (most) companies also adopt a naming convention throughout their documentation. Throughout this site:
|
|
Variables and Their Data Types |
The amount of memory space necessary to store a variable is also referred to as a data type. A data type provides two valuable pieces of information to the compiler: what amount of space the variable will use, what kind of information will be allowed in that space.
After declaring a variable, the compiler reserves a space in memory for that variable:
A variable, any variable, occupies more that one small “cell†of space in memory. It will always be your responsibility to decide how much space a variable needs, based on your goal.
C You In |
Besides the cout extractor, C++ is equipped with another operator used to request values from the user. The user usually provides such a value by typing it using the keyboard. The cin (pronounce “see inâ€) operator is used for that purpose; it displays a blinking cursor on the monitor to let the user know that a value is expected. Unlike the cout operator, the cin uses two greater than signs “>>†followed by the name of the expected value. The syntax of the cin operator is: cin >> valueName; If you are requesting many values from the user, you can write a statement that would act accordingly by separating values with as many >> operators as necessary. For example, to request a first name, last name, and an age on the same line, you could use: cin >> firstName >> lastName >> Age; |
The Numeric Systems |
Introduction |
When you decide to use the computer, if it is off, the first thing you do is to turn it on. As the computer is coming up ( it is booting), you can hear a noise (but many computers now are (very) quiet). It sounds like things are happening inside; things you usually don't care about. In essence, when that noise stops, if everything went fine, the computer “loads†what is called an operating system. Although the computer is up and you can see some pictures on the screen, no program other than the operating system (and some things we are not concerned about, called utilities) is available: you have to tell the computer, “I want to use program Aâ€. After clicking a program of your choice, once again you would hear a noise. Depending on the called program, some applications take longer to come up than others. When you call a program, there is an initial setup that the program has to go through to be ready. 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 use the computer. |
To write your programs, you will be using alphabetic characters 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 symbols 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 you have typed an instruction, the compiler would translate it to |
machine language. Why not send your instructions directly to the computer? This is because the computer does not understand the language you and I speak or write. 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 the computer memory using a certain amount of space for each instruction or each item you use. How much space is necessary? How does the compiler figure out that space? There are three numbering systems that will be involved in your programs, with or without your intervention. The numeric system provides the counting techniques that you use everyday. The hexadecimal system is an intermediary system that allows you to know how the computer deals with numbers. The binary system is the actual system that the computer uses to find out (almost) everything in your program. |
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. Why learn the binary system? You need to know what the binary system looks like because you will be writing instructions to the computer, and the computer does not understand English. |
The Decimal System |
The numeric system that we have always used uses a set of 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 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). Why use the decimal system? Because, to represent numbers, that is the only system that you and I are familiar with. |
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 Latin language 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. Once again, to produce a 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?
Why learn or use the hexadecimal system? Because the computer does not understand the decimal system, which is our everyday base of counting items, and because we do not understand or are not familiar with the binary system, the hexadecimal system provides an intermediary system. Also, the hexadecimal system represents shorter words to represent the same numbers in the decimal system. |
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. |
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. A piece of information in the computer is called a datum; and the plural is data. Sometimes, the word data is used for both singular and plural. The computer represents data using only a 0 or 1 values. To make an illustration, let's consider that a computer uses a small box to represent such a value. This small box can have only one of two states. When the box is empty, we will give it a value of 0. When the box is full, we give it a value of 1. The box can have only one of these two values. |
Since this box can have only one of two states, consider that you can use it to represent anything that could assume one out of two states. Examples include: True-False; Parent-Child; On-Off; Discount-NoDiscount; Male-Female; Yes-No, etc. This technique of representing values is called 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 this is valid for the computer, the Intel microprocessors cannot validate a variable at this level; but eventually, you will be able to manipulate data at the bit level. 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 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. 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 nibble, 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 nibble, 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 box 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. As you can see, a nibble is represented by a group of 4 bits. This 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. How do you reconcile such a number to a nibble? The technique used to complete and fill out the nibble 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 nibble are 0, you have the lowest value you can get, 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 nibble. 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 is very difficult to read when a value combines various bit representations. To make your life a little 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: |
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. For this reason, you may have to memorize it. A nibble, which is a group of four consecutive bits, has a minimum and maximum values on each system as follows: |
|
Although the C++ compiler recognizes a group of four consecutive bits, you cannot store any variable in a nibble. You can, however, manipulate the bits of a nibble. |
A Byte |
Representing a Byte |
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. A byte is considered as being made of two nibbles. The right nibble, made of the right 4 bits, is called the Low Order nibble or LO nibble. The left nibble, made of the left 4 bits, is called the High Order nibble or HI nibble.
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, we will represent bits in groups of four. Instead of writing 00000000, we will 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 nibble, 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 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 nibble, we get the following table: |
|
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 use the cout << operator and include the character between single-quotes, as follows: |
#include <iostream> using namespace std; int main() { cout << 'a'; return 0; }
Character Variables |
A byte is used to hold a single character. A character is an individual symbol that displays on your screen. It could be:
To declare a variable as a character, use the C++ keyword char followed by a valid C++ name. Here is an example: char Gender; With a byte variable declared like that, you can give the variable a starting value. Giving a value to a variable is referred to as initializing it. Initializing a variable is done with the = operator. The syntax used is: VariableName = Value; Since a char variable represents one symbol, to initialize it, enclose the initial value in single quotes. Here is an example: char Answer = ‘y’; You can also initialize a variable by including its value between parentheses as follows; char Answer(‘y’); To display the value of an initialized variable, use the cout << extractor and type the name of the variable. Here is an example: #include <iostream> using namespace std; int main() { char category = 'H'; cout << "Category: " << category; cout << endl; return 0; } If the character is of a signed category, you can declare it as a signed character. This type of variable would be an 8-bit integer whose value can range from –128 to +127. Here is an example: #include <iostream> using namespace std; int main() { signed char category = 'D'; cout << "Category: " << category << endl; return 0; } You can also declare a positive character as unsigned char. Here is an example: #include <iostream> using namespace std; int main() { char letter = 'L'; char category = 'n'; unsigned char sound('x’); cout << "Pick " << Pick; cout << category; cout << "Sound " << sound; return 0; } To request a byte variable, type the name of the variable on the right side of the cin >> extractor followed by a semi-colon as follows: #include <iostream> using namespace std; int main() { char Satisfaction, answer; signed char ageCategory, size; cout << "From A to Z, enter a character as your level of satisfaction: "; cin >> satisfaction; cout << "Age category(t=teen/a=Adult/s=Senior): "; cin >> ageCategory; cout << "Are you drunk(y=Yes/n=No)? "; cin >> answer; cout << "Enter your size(s=Small/m=Medium/l=Large): "; cin >> size; cout << "\nSatisfaction: " << Satisfaction; cout << "\nAge category: " << AgeCategory; cout << "\nYour answer: " << Answer; cout << "\nYour size: " << Size; return 0; } To keep the integer value of a char positive, you can declare it as an unsigned char. Its value would then range from 0 to 255.
When you use alphabetic characters in your program, the compiler considers them as numbers but converts each to its corresponding character following the ASCII list. Counting decimal values starting at 0, the first 32 characters actually do not display anything on the screen: they are called non-printing characters. They are obtained from pressing Ctrl and an alphabetic letter or a symbol. The exception is that the 8th to 12th characters are used to control some of the characters and they are called escape sequences. To use one of these escape sequences, you include it preceded by a backslash; you can include both in single-quotes. For example, the \n is used to ask the compiler to stop the line and start the remaining program to the next line; this is referred to Carriage Return – Line Feed. The \n escape sequence could be used as follows: #include <iostream> using namespace std; int main() { cout << "Sydney\nAustralia\n"; return 0; } Besides the \n escape sequence, you can also use the endl keyword to move the cursor to the next line. Here is the list of escape sequences:
|
A Word |
Representing a Word |
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 most fundamental representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits in 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The maximum binary value represented by a word is 1111 1111 1111 1111. The minimum decimal value of a word is 0. 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 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. 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 |
Short Integers |
A word, which is a group of 16 contiguous bits or 2 bytes, is used to represent a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. Since the Byte is used only to represent a character, whenever you plan to use a number in your program, the minimum representation you should/must use is a word. An algebraic natural number is also called an integer. The smallest integer you can store in a word is declared with the short keyword followed by a name. 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: |
#include <iostream> using namespace std; int main() { short number1, number2; cout << "Enter a number between -32768 and 32767: "; cin >> number1; cout << "Enter another number: "; cin >> number2; cout << "\nThe numbers you entered were\n"; cout << "\tNumber 1: " << number1 << "\n"; cout << "\tNumber 2: " << number2 << "\n"; return 0; }
By default, a short integer is signed. You can also explicitly declare such a variable as a signed short. Here is an example: signed short XCoord; If the integer must be positive, you should declared as an unsigned short. The unsigned short is used to identify a 16-bit positive integer whose value would range from 0 to 65535. |
Practical Learning: Using Short Integer Variables |
#include <iostream> using namespace std; int main() { unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order" << "\nItem Type Qty" << "\nShirts: " << shirts << "\nPants: " << pants << "\nDresses: " << dresses << "\nTies: " << ties << "\n\n"; return 0; } |
-=- Georgetown Cleaning Services -=- Enter number of shirts: 6 Enter number of pants: 2 Enter number of dresses: 3 Enter number of ties: 4 ==================================== -=- Georgetown Cleaning Services -=- ==================================== Customer Order Item Type Qty Shirts: 6 Pants: 2 Dresses: 3 Ties: 4 |
A Double-Word |
Representing a Double-Word |
A double-word is a group of two consecutive Words. This means that a double-word combines 4 bytes, or 8 nibbles, or 32 bits. The bits, counted from right to left, start at 0 and end at 31. |
The most right bit, bit 0, is called the Low Order bit or LO bit or LOBIT. The most left bit, bit 31, is called the High Order bit or HI bit or HIBIT. The other bits are called using their positions. The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the Low Order Byte, or LO Byte. It is sometimes referred to as LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the High Order Byte, or HI Byte or HIBYTE. The other bytes are called by their positions. The group of the right 16 bits, or the right Word, is called the Low Order Word, or LO Word, or LOWORD. The group of the left 16 bits, or the left Word, is called the High Order Word, or HI Word, or HIWORD. |
The minimum binary number you can represent with a double-word is 0 The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula giving a 1 value to each bit: |
|
|
|
|
1*231+1*230+1*229 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 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 = 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 4,286,578,708 The minimum hexadecimal value you can store in a word is 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F: |
|
Using Integers |
A double-word is large enough to contain double the amount of data that can be stored in a word. This is equivalent to 32 bits or 4 bytes or 4294967295. Therefore, a double-word is used for large numbers that would not fit in a word. An integer is a natural number typically used to count items. For an integer variable whose value requires more memory space than a word can hold, declare it using the int keyword. The integer data type is used for a variable whose value can range from –2,147,483,648 to 2,147,484,647. Here is an example: |
#include <iostream> using namespace std; int main() { int coordX, coordY, coordZ; cout << "Enter the coordinates of point A\n"; cout << "Horizontal X = "; cin >> coordX; cout << "Vertical Y = "; cin >> coordY; cout << "Depth Z = "; cin >> coordZ; cout << "\nOn a cartesian system, point A is located at"; cout << "\n\tX = " << coordX; cout << "\n\tY = " << coordY; cout << "\n\tZ = " << coordZ; return 0; }
When executed, the program would produce: Enter the coordinates of point AHorizontal X = -12Vertical Y = 8Depth Z = 6On a cartesian system, point A is located at X = -12 Y = 8 Z = 6Press any key to continue... The signed is used to designate an integer variable whose value could be negative or positive. You can declare such a variable using one of the following: signed distanceRange; signed int velocity; When declared with int, an integer is considered as signed. You can also explicitly declared such an integer as signed int. Here is an example: signed int pagePosition; If the variable must be positive, you can declared it an unsigned int. The unsigned int is used to identify a 32-bit positive integer variable whose value would range from 0 to 2,147,484,647. Here is an example: unsigned int pageCount; An unsigned integer can also be declared simply with the unsigned keyword. Here is an example: |
#include <iostream> using namespace std; int main() { unsigned dayOfBirth, monthOfBirth, yearOfBirth; cout << "The following pieces of information " << "are required for each student\n"; cout << "Day of Birth: "; cin >> dayOfBirth; cout << "Month of Birth: "; cin >> monthOfBirth; cout << "Year of Birth: "; cin >> yearOfBirth; cout << "\nStudent's Date of Birth: " << dayOfBirth << "/" << monthOfBirth << "/" << yearOfBirth; return 0; }
Practical Learning: Using Integer Variables |
|
Long Integers |
An integer variable whose value should be positive can also be declared with the long keyword. The long keyword designates a positive 32-bit integer whose value ranges from 0 to 4,294,967,295. Here is an example: long countryArea; To enforce the long integer being positive, you can declare its variable as an
unsigned long. The following program illustrates that: |
#include <iostream> using namespace std; int main() { long USPopulation; unsigned long USArea; cout << "What is the area of the US? "; cin >> USArea; cout << "What is the population of the US? "; cin >> USPopulation; cout << "\nCharacteristics of the US"; cout << "\n\tArea = " << USArea << "\n\tPopulation = " << USPopulation; return 0; }
Floating-Point Numbers |
Floating-Point Numbers With Single-Precision |
The integers we have used so far have the main limitation of not allowing decimal values. C++ provides floating identifier values that would solve this problem. The most fundamental floating variable is declared with the float keyword. The float is a 4 Byte real number that ranges from 3.4 x 10-38 to 3.4 x 1038. To declare a floating variable, use the float keyword followed by the name of the variable. Here are examples: float side; float length; To initialize a floating variable, after declaring it, assign it a value using the Assignment operator “=â€, like this: float priceSoda; priceSoda = 0.85; You can also initialize the variable using the parentheses, like this: float priceOrangeJuice(2.25); To request a floating-point variable from the user, use the cin >> operator, like this cin >> variable; Like an initialized variable, you can perform any desired operation on such a variable. Here is an example program that requests the side of a square and then calculates the perimeter and the area: |
#include <iostream> using namespace std; int main() { float side, perimeter, area; cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout << "Characteristics of the square:"; cout << "\nSide: " << side; cout << "\nPerimeter: " << perimeter; cout << "\nArea: " << area; return 0; }
Floating-Point Numbers With Double-Precision |
When a variable is larger than the float can handle and requires more precision, you should use the double identifier. The double-precision identifier is an 8 Byte decimal or fractional number ranging from 1.7 x 10-308 to 1.7 x 10308. Here is an example: |
#include <iostream> using namespace std; int main() { float side, perimeter, area; cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout << "Characteristics of the square:"; cout << "\nSide: " << side; cout << "\nPerimeter: " << perimeter; cout << "\nArea: " << area; return 0; }
For an even larger variable, use the 10 Byte real data type identified as a long double data type that ranges from 3.4 x 10-4932 to 1.1 x 104932. Here is an example that uses the long double data type: |
#include <iostream> using namespace std; int main() { long double radius = 15.625, Radius = 18.125; long double area, Area, TotalArea; Area = Radius * Radius * 3.14159; area = radius * radius * 3.14159; TotalArea = Area - area; cout << "Properties of the plate"; cout << "\nExternal Radius: " << Radius; cout << "\nInternal Radius: " << radius; cout << "\nArea: " << TotalArea; return 0; }
Practical Learning: Using Floating-Point Numbers |
|
Introduction to Strings |
A Group of Characters |
A group of characters is called an array. This is a study we will cover when learning about arrays. For now, if you want to use a group of characters of any kind, declare a variable starting with a char data type, followed by a valid name for the variable, followed by an opening square bracket “[“, followed by a number of characters, followed by a closing square bracket “]â€, and ended with a semi-colon. The syntax to declare a group of characters is: char VariableName[NumberOfCharacters]; The char keyword is required to let the compiler know that you want to create a variable of type char. The created variable must have a valid name. The number of characters, called the dimension of the array, should be an estimate; for example, if you want to request employees’ first names, type a number that you think would represent the largest name possible. The maximum number should be 80, but the average and a good regular number should be between 12 or 20. To represent an address or a similar long group of characters, use a dimension between 32 and 50. Examples of declaring arrays of characters are: char FirstName[12]; char LastName[12]; To initialize an array of characters, do not specify the dimension and leave the square brackets empty. You can use the assignment operator and include the initialized variable in double-quotes. Another technique, is to include the value between parentheses. Here is a program with two techniques of initializing arrays of characters: #include <iostream> using namespace std; int main() { char University[] = "University of the District of Columbia"; char Faculty[]("Computer sciences"); cout << "Welcome to the Student Orientation Program.\n"; cout << "For your studies, we have selected:\n"; cout << "Institution: " << University << "\n"; cout << "Faculty: " << Faculty << "\n"; return 0; } To request an array from the user, simply type the name of the array variable on the right side of the cin >> operator. Here is an example: #include <iostream> using namespace std; int main() { char FirstName[12]; char LastName[12]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "\nFull Name: " << FirstName << " " << LastName; cout << endl; return 0; } To request a group of words using an array, use one of the following functions: cin.getline( VariableName, Dimension); cin.getline(VariableName, Dimension, Delimeter); To use the array variables, change the content of the file as follows: #include <iostream> using namespace std; int main() { char FirstName [20], LastName [20]; char Address [40]; char JobPerformed [80]; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> ws; cin.getline(FirstName, 20); cout << "Last Name: "; cin >> ws; cin.getline(LastName, 20); cout << "Address: "; cin >> ws; cin.getline(Address, 40); cout << "Describe the job performed on the customer's car in 100 words or less:\n"; cin >> ws; cin.getline(JobPerformed, 80); cout << "\nCPAP Invoice # 1202"; cout << "\nCustomer Name: " << FirstName << " " << LastName; cout << "\nAddress: " << Address; cout << "\nJob Performed: " << JobPerformed; cout << "\n\n"; return 0; } |
Practical Learning: Using Strings |
The following exercise was tested only in Microsoft Windows. The cin >> ws operation may not work on other operating systems but you would have to test it for yourself. Thanks. |
|
Strings |
A string is a character, a group of characters, or an empty space that you want the compiler to treat “as isâ€. Besides using an array of characters, a special library called the Standard Template Library provides an alternative. You can declare a string using the string keyword. To use a string in your program, first include the string library using the using namespace keywords followed by std;. In your program, declare a variable starting with the word string followed by a valid name for the variable. Here are examples: string Continent; When requesting its value from the user, by default, the string identifier is used to get only a one-word variable. Here is an example program that requests a first and last names: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Enter first name: "; cin >> FirstName; cout << "Enter last name: "; cin >> LastName; cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n"; return 0; } You can initialize a string variable of any length. One technique is to use the assignment operator and include the string in double-quotes. Here is an example: string UN = "United Nations"; cout << "The " << UN << " is an organization headed by a Secretary General"; Another technique involves using parentheses following the name of the string variable, and including the string in double-quotes. Here is an example: string BookTitle("Drugs, Sociology, and Human Behavior."); cout << "For our class next week, please read \"" << BookTitle;cout << "\""; If you want to request the value of the variable from the user, you should use the getline function. To use the getline function, follow this formula: getline(cin, StringName); Inside of the parentheses, the word cin informs the compiler that the request will come from an external source, mainly the user typing from the keyboard. The StringName is the name you declared the variable with. The getline() function expects that the user will press Enter to end the sentence; the end line character is ‘\n’. Here is an example program that requests strings of any length from the user: #include <iostream> #include <string> using namespace std; int main() { string MusicAlbum; string TrackTitle; cout << "Welcome to Radio Request where the listeners select their songs:\n"; cout << "Type the album name: "; getline(cin, MusicAlbum); cout << "Type the song title: "; getline(cin, TrackTitle); cout << "\nNow for your pleasure, we will play: " << TrackTitle << "\nfrom the " << MusicAlbum << " wonderful album.\n\n"; return 0; } If you want the user to end the sentence with another character such as * or !, use the following function getline(cin, StringName, Delimiter); The following example uses the = symbol as the end character of the sentence: string Address; cout << "Enter your address. To end, type = "; getline(cin, Address, '='); cout << "\nSo, you live at: " << Address; Here is an example: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "\n\nCPAP Invoice # 1202"; cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n"; return 0; } When requesting a string made of various words, such as an address, you can use the getlin() function as follows: #include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; string Address; string JobPerformed; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "Address: "; getline(cin, Address); cout << "Describe the job performed on the customer's car:\n"; getline(cin, JobPerformed); cout << "\n\nCPAP Invoice # 1202"; cout << "\nCustomer Name: " << FirstName << " " << LastName; cout << "\nAddress: " << Address; cout << "\nJob Performed: " << JobPerformed << "\n\n"; return 0; } |
|
||
Previous | Copyright © 1998-2015, FunctionX, Inc. | Next |
|