Académique Documents
Professionnel Documents
Culture Documents
???????????????
1
FunctionX Press
2
Table of Contents
Introduction................................................................................................................. 12
© FunctionX, Inc. 3
2.5.3 Escape Sequences..............................Error! Bookmark not defined.
2.5.4 Boolean Variables .............................Error! Bookmark not defined.
2.6 A Word ........................................................Error! Bookmark not defined.
2.6.1 Representing a Word ........................Error! Bookmark not defined.
2.6.2 Short Integers.....................................Error! Bookmark not defined.
2.7 A Double-Word..........................................Error! Bookmark not defined.
2.7.1 Representing a Double-Word..........Error! Bookmark not defined.
2.7.2 Using Integers....................................Error! Bookmark not defined.
2.7.3 Long Integers .....................................Error! Bookmark not defined.
2.7.4 Enumerations.....................................Error! Bookmark not defined.
2.8 Floating-Point Numbers............................Error! Bookmark not defined.
2.8.1 Floating-Point Variables ..................Error! Bookmark not defined.
2.8.2 Double-Precision Numbers .............Error! Bookmark not defined.
2.8.3 Arrays of Characters .........................Error! Bookmark not defined.
© FunctionX, Inc. 4
4.3.4 Incrementing a Number....................Error! Bookmark not defined.
4.3.5 Pre and Post-Increment ....................Error! Bookmark not defined.
4.3.6 Decrementing – Pre and Post-Decrementing Error! Bookmark not
defined.
4.3.7 Techniques of Incrementing and Decrementing a Variable ....Error!
Bookmark not defined.
4.4 Bit Manipulations ......................................Error! Bookmark not defined.
4.4.1 Introduction........................................Error! Bookmark not defined.
4.4.2 Bits Operators: The Bitwise NOT Operator ~..... Error! Bookmark
not defined.
4.4.3 Comparing Bits: The Bitwise AND Operator &. Error! Bookmark
not defined.
4.4.4 Comparing Bits: The Bitwise OR Operator | Error! Bookmark not
defined.
4.4.5 Comparing Bits: The Bitwise-Exclusive XOR Operator ^.....Error!
Bookmark not defined.
4.4.6 Bit Shift Operators: The Left Shift << .......... Error! Bookmark not
defined.
4.4.7 Bit Shift Operators: The Right Shift >>........ Error! Bookmark not
defined.
4.5 Variable Casting: An Introduction..........Error! Bookmark not defined.
4.5.1 C Casting ............................................Error! Bookmark not defined.
4.5.2 Operator Precedence and DirectionError! Bookmark not defined.
© FunctionX, Inc. 5
6.4.2 Global Definitions.............................Error! Bookmark not defined.
6.4.3 Namespaces and External Functions............. Error! Bookmark not
defined.
6.5 C++ Built-in Functions.............................Error! Bookmark not defined.
6.5.1 Asserting a Value or an Expression............... Error! Bookmark not
defined.
6.5.2 Mathematic Functions......................Error! Bookmark not defined.
© FunctionX, Inc. 6
9.1.3 Initializing an Array..........................Error! Bookmark not defined.
9.1.4 Processing an Array..........................Error! Bookmark not defined.
9.2 Operations on Arrays................................Error! Bookmark not defined.
9.2.1 The Size of an Array.........................Error! Bookmark not defined.
9.2.2 Algebraic Operations on Array Members ..... Error! Bookmark not
defined.
9.2.3 Requesting Array Members.............Error! Bookmark not defined.
9.2.4 Arrays and Functions........................Error! Bookmark not defined.
9.3 Multidimensional Arrays..........................Error! Bookmark not defined.
9.3.1 Introduction........................................Error! Bookmark not defined.
9.3.2 Two-Dimensional Arrays ................Error! Bookmark not defined.
9.3.3 Initializing a Two-Dimensional Array .......... Error! Bookmark not
defined.
9.3.4 Multidimensional Arrays.................Error! Bookmark not defined.
© FunctionX, Inc. 7
11.4.5 ..The strncat() Function......................Error! Bookmark not defined.
11.4.6 ..The strcpy Functtion.........................Error! Bookmark not defined.
11.4.7 ..The strncpy() Function.....................Error! Bookmark not defined.
11.4.8 ..The strdup() Function.......................Error! Bookmark not defined.
11.5 Comparing Strings...................................Error! Bookmark not defined.
11.5.1 ..The strcmp() Function......................Error! Bookmark not defined.
11.5.2 ..The strncmp() Function ...................Error! Bookmark not defined.
11.5.3 ..The stricmp() Function ....................Error! Bookmark not defined.
11.5.4 ..The strnicmp() Function ..................Error! Bookmark not defined.
11.6 Working With Individual Characters ...Error! Bookmark not defined.
11.6.1 ..The strchr() Function........................Error! Bookmark not defined.
11.6.2 ..The strrchr() Functionn....................Error! Bookmark not defined.
11.7 Working With Sub-St rings.....................Error! Bookmark not defined.
11.7.1 ..The strstr() Function.........................Error! Bookmark not defined.
11.8 Working With Character Cases.............Error! Bookmark not defined.
11.8.1 ..The strlwr() Function .......................Error! Bookmark not defined.
11.8.2 ..The strupr() Function .......................Error! Bookmark not defined.
11.9 Formatting Strings...................................Error! Bookmark not defined.
11.9.1 ..The sprintf() Function......................Error! Bookmark not defined.
© FunctionX, Inc. 8
13.3.2 ..The gets() Function...........................Error! Bookmark not defined.
13.3.3 ..C How to Input Data ........................Error! Bookmark not defined.
13.4 A Character: Its Case, Value, and Meaning........ Error! Bookmark not
defined.
13.4.1 ..Character Cases.................................Error! Bookmark not defined.
13.4.2 ..Validating a Character .....................Error! Bookmark not defined.
13.5 Ending a Program....................................Error! Bookmark not defined.
13.5.1 ..Exiting a Program.............................Error! Bookmark not defined.
13.5.2 ..Aborting a Program..........................Error! Bookmark not defined.
13.5.3 ..Terminating a Program....................Error! Bookmark not defined.
© FunctionX, Inc. 9
16.3.1 ..Defining a Union...............................Error! Bookmark not defined.
16.3.2 ..Using a Union....................................Error! Bookmark not defined.
16.4 Variables Scope and Lifetime ................Error! Bookmark not defined.
16.4.1 ..Condition Scope................................Error! Bookmark not defined.
16.4.2 ..Block Scope.......................................Error! Bookmark not defined.
16.4.3 ..Function Scope..................................Error! Bookmark not defined.
16.4.4 ..File Scope...........................................Error! Bookmark not defined.
© FunctionX, Inc. 10
19.3.1 ..Using an Enumerator as an Object Member Error! Bookmark not
defined.
19.3.2 ..Mixing Objects..................................Error! Bookmark not defined.
19.3.3 ..An Object as a Member Variable ...Error! Bookmark not defined.
19.4 Functions, Classes, and Friendship.......Error! Bookmark not defined.
19.4.1 ..Friend Functions of a Class.............Error! Bookmark not defined.
19.4.2 ..A Class as a Friend ...........................Error! Bookmark not defined.
APPENDIX................................................................................................................. 131
Appendix A: Clearing the Screen ......................Error! Bookmark not defined.
Using the system() Function .........................Error! Bookmark not defined.
Borland's Function of Clearing the Screen .Error! Bookmark not defined.
Appendix B: Operator Precedence.....................Error! Bookmark not defined.
Appendix C: Relationships on the Numeric Systems ........................................132
Converting A Byte From Binary to Decimal................................................132
Converting Any Number From Binary To Decimal....................................132
Converting A Byte From Binary to Hexadecimal........................................133
Converting Any Number Fro m Binary to Hexadecimal.............................133
Converting A Byte From Decimal to Binary ................................................134
Converting Any Number From Decimal to Binary ......................................134
© FunctionX, Inc. 11
Converting A Byte From Decimal to Hexadecimal.....................................138
Converting Any Number From Decimal to Hexadecimal..........................138
Converting a Byte From Hexadecimal to Binary .........................................138
Converting Any Number From Hexadecimal to Binary .............................139
Converting a Byte From Hexadecimal to Decimal......................................139
Converting Any Number From Hexadecimal to Decimal..........................140
© FunctionX, Inc. 12
C++ Fundamentals Introduction
Introduction
This book assumes no prior knowledge of any programming language from you. To use
this book, you must have installed a C++ compiler on your computer in order to follow
the programs in this book. If you are using a Linux or Unix operating systems, everything
should have been installed already as they ship with C and C++ compilers. If you are
using Linux, we recommend you install or make sure that KDevelop is installed or any
other visual programming environment that supports the C++ language. This would make
your programming a little easier. Alternatively, you can get Dev-C++. Microsoft
Windows does not ship with any C++ compiler. You must explicitly make sure that you
have installed a C++ environment. The cheapest you can get is Dev-C++ from the
http://www.bloodshed.com web site.
In this book, Bcb means Borland C++ Builder. MSVC means Microsoft Visual C++.
© FunctionX, Inc. 13
C++ Fundamentals Chapter 3 Techniques of Using Variables
Chapter 3:
Techniques of Using Variables
? Unary Operators
? Algebraic Operators
? C++ Operators
? Bit Manipulations
© FunctionX, Inc. 14
C++ Fundamentals Chapter 3 Techniques of Using Variables
The typedef keyword is required to let the compiler know that you are creating a new
identifier. The DataType is any of those we have learned so far. It could be an int, an
unsigned int, a char, a double, etc. An example of declaring a typedef is:
In this case, NumberOfStudents is just a new name for an int. It can be used as a new
identifier exactly as if you were using an int. Here is an example that redefines an int data
type:
#include <iostream.h>
int main()
{
typedef int NumberOfStudents;
return 0;
}
© FunctionX, Inc. 15
C++ Fundamentals Chapter 3 Techniques of Using Variables
3.1.2 Constants
A constant is a value that does not change. There are various categories of constants you
will be using in your programs. To make their management easier, these constant values
have been categorized and defined in particular libraries. Throughout this book, you will
be using them.
The algebraic numbers you have been using all the time are constants because they never
change. Examples of constant numbers are 12, 0, 1505, or 88146. Therefore, any number
you can think of is a constant.
Every letter of the alphabet is a constant and is always the same. Examples of constant
letters are d, n, c.
Some characters on your keyboard represent symbols that are neither letters nor digits.
These are constants too. Examples are #, &, |, !.
Some values would be constant by default, but their constancy sometimes depends on the
programmer. For example, one programmer can define a const PI as 3.14; another
programmer can decide that the constant PI would be 3.14159. Therefore, you will be
defining your own constant values as you see fit for the goal you are trying to achieve.
There are two main techniques you use to display a constant value in C++. To simply
display it using the cout << extractor, you can use its value on the right side of the <<
symbols. You can also define it first using an appropriate name, and then using that name
to display the constant.
#include <iostream.h>
int main()
{
cout << 28;
The safest technique of using a constant is to give it a name. This allows you to manage it
from one standpoint. For example, if you plan to use a number such as 3.14 that
represents PI, you can simply use the constant 3.14. Imagine you want to use 3.14 in
various sections of the program such as in different functions. If you decide to change the
number from 3.14 to 3.14159 or another value, you would have to find every mention of
3.14; this can lead to a programming error. The alternative is to declare a variable and
assign it the desired value. The new and defined value is called a constant.
There are two main techniques used to create constant values. The old way, which was
used with the C language and widely used in documentation and help files consists of
using the define keyword. The syntax of creating a constant using the define keyword is:
The # symbol and the define word are required; they inform the compiler that the
following name represents a constant. The ConstantName represents a valid name for the
desired constant; the name follows the same rules we learned for defining names in C++.
The ConstantValue can be a character, an integer, a floating-point value, or an
© FunctionX, Inc. 16
C++ Fundamentals Chapter 3 Techniques of Using Variables
expression. If the constant value is an integer or a floating-point value, you can type it. If
the value is a character, include it between single-quotes. The definition of the constant
does not end with a semi -colon. Examples of declaring constants are:
Another technique of creating a constant is by using the const keyword. The syntax of
using the const keyword is:
Or
The const keyword is required to inform the compiler that you are creating a constant.
The ConstantName specifies the name of the constant value; it follows the rules we have
applied for the names of variables. The DataType, although optional, is used to let the
compiler know what kind of variable it is. If you do not specify a data type, the compiler
would assume that the constant is an integer. Therefore, make it a habit to always specify
the data type when creating a constant using the const keyword. The data type can be any
of those we have learned. Use the assignment operator to assign the desired constant to
the name.
Another category of constants are those that are part of the C++ compiler. Those
constants have names they can be recognized with. For example, the minimum value of
the short integer is SHRT_MIN. In the same way, the maximum short integer is identified
by SHRT_MAX. You can use either of these constants as follows:
#include <iostream.h>
#include <limits.h>
int main()
{
cout << "The minimum signed character: " << SCHAR_MIN << "\n";
cout << "The maximum signed character: " << SCHAR_MAX << "\n";
cout << "The minimum short integer is: " << SHRT_MIN << "\n";
cout << "The maximum short integer is: " << SHRT_MAX << "\n\n";
return 0;
}
According to the C++ Standard, the integral constants are defined in the climits library
but they can be defined as one compiler chooses to. For example, in Borland C++
Builder, they are in the _lim.h library. In the KDevelop and Microsoft C++ compilers
they are in the limits.h file.
© FunctionX, Inc. 17
C++ Fundamentals Chapter 3 Techniques of Using Variables
In the same way, C++ provides constant double-precision numbers in the cfloat library.
These constants are:
The C++ Standard also defines a constant as NULL. This constant is used to designate
that a pointer does not hold a valid value. The NULL constant is defined in the cstddef
library.
3.2 Namespaces
A namespace is a section of code, delimited and referred to using a specific name. A
namespace is created to set apart a portion of code with the goal to reduce, otherwise
eliminate, confusion. This is done by giving a common name to that portion of code so
that, when referring to it, only entities that are part of that section would be referred to.
The creation of a namespace starts with the (required) namespace keyword followed by a
name that would identify the section of code. The name follows the rules we have been
applying to C++ names. A namespace contains a body; this is where the entities that are
part of the namespace would be declared or defined. The body of the namespace starts
with an opening curly bracket “{” and ends with a closing curly bracket “}”. Here is an
example of a simple namespace:
namespace Mine
{
int a;
}
© FunctionX, Inc. 18
C++ Fundamentals Chapter 3 Techniques of Using Variables
The entities included in the body of a namespace are referred to as its memb ers.
Mine::a;
Once you have access to a namespace member, you can initialize it or display its value
using the cout extractor operator. Here is an example:
#include <iostream.h>
namespace Mine
{
int a;
}
int main()
{
Mine::a = 140;
Value of a = 140
When creating a namespace, you can add as many members as you see fit. When
necessary, you can use the scope access operator to call anyone of them as needed. Here
is an example:
#include <iostream.h>
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}
int main()
{
InterestAndDiscount::Principal = 3250;
InterestAndDiscount::Rate = 0.1225; // =12.25%
InterestAndDiscount::Time = 2;
© FunctionX, Inc. 19
C++ Fundamentals Chapter 3 Techniques of Using Variables
return 0;
}
You can also request the values of the members of a namespace from the user.
Remember to use the scope access operator whenever you need to access the member of
a namespace. Here is an example:
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}
int main()
{
cout << "Interest and Discount \n";
cout << "Principal: $";
cin >> InterestAndDiscount::Principal;
cout << "Rate (example 8.75): ";
cin >> InterestAndDiscount::Rate;
cout << "Number of Years: ";
cin >> InterestAndDiscount::Time;
return 0;
}
Interest Calculation
Principal: $12500.00
Rate: 7.25%
Time: 10 years
The member variable of a namespace can also mixed with a variable that is locally
declared in a function. All you have to do is make sure that you qualify the member of
the namespace so the compiler would be able to locate it. Here is an example:
#include <iostream.h>
namespace InterestAndDiscount
{
© FunctionX, Inc. 20
C++ Fundamentals Chapter 3 Techniques of Using Variables
double Principal;
double Rate;
int Time;
}
int main()
{
double Interest;
double MaturityValue;
Interest = InterestAndDiscount::Principal *
(InterestAndDiscount::Rate/100) *
InterestAndDiscount::Time;
MaturityValue = InterestAndDiscount::Principal + Interest;
return 0;
}
To call a namespace, on the section of the program where you need to access the
members, type:
Both the using and the namespace keywords are required by the compiler. The
NamespaceName represents the name of the namespace whose member(s) you want to
access. Using this technique, the above program can be written:
#include <iostream.h>
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
}
© FunctionX, Inc. 21
C++ Fundamentals Chapter 3 Techniques of Using Variables
int main()
{
using namespace InterestAndDiscount;
double Interest;
double MaturityValue;
return 0;
}
Loan Processing
Principal: $2500
Rate: 12.15%
Time: 4 years
Interest: $1215
Maturity Value: $3715
In a variable intensive program (we are still inside of one function only) where a local
variable holds the same name as the member of a namespace that is being accessed with
the using namespace routine, you will be sensitive to the calling of the same name
variable. When manipulating such a name of a variable that is present locally in the
function as well as in the namespace that is being accessed, the compiler will require
more precision from you. You will need to specify what name is being called.
© FunctionX, Inc. 22
C++ Fundamentals Chapter 3 Techniques of Using Variables
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}
To access the member of a namespace, use the scope access operator appended to its
name and call the desired member. Here is an example:
#include <iostream.h>
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}
int main()
{
InterestAndDiscount::Principal = 12500; // $
InterestAndDiscount::Rate = 8.25; // %
InterestAndDiscount::Time = 5; // Years
InterestAndDiscount::Discount = InterestAndDiscount::Rate / 100;
© FunctionX, Inc. 23
C++ Fundamentals Chapter 3 Techniques of Using Variables
InterestAndDiscount::Interest = InterestAndDiscount::Principal *
InterestAndDiscount::Discount *
InterestAndDiscount::Time;
InterestAndDiscount::MaturityValue = InterestAndDiscount::Principal +
InterestAndDiscount::Interest;
BuyAndSell::OriginalPrice = 250; // $
BuyAndSell::TaxRate = 16.00; // %
BuyAndSell::Discount = 20.00; // %
BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
BuyAndSell::TaxRate / 100;
BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
BuyAndSell::Discount / 100;
BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
BuyAndSell::TaxAmount -
BuyAndSell::DiscountAmount;
return 0;
}
Using the scope access operator like that, you can perform any operation on any member
of one namespace applied to a member of another namespace.
We saw earlier that the using namespace routine allows accessing the members of a
namespace. After typing it, if the name of a variable appears under a using namespace,
the compiler would need to reconcile or identify it; if the name of such a variable is not
recognized as part of the namespace that is being accessed, the program would not
compile. For example, here is an example that uses two using namespace routines:
#include <iostream.h>
namespace InterestAndDiscount
{
double Principal;
double Rate;
int Time;
double Interest;
double Discount;
double MaturityValue;
}
namespace BuyAndSell
© FunctionX, Inc. 24
C++ Fundamentals Chapter 3 Techniques of Using Variables
{
double OriginalPrice;
double T axRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
}
int main()
{
using namespace InterestAndDiscount;
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years
return 0;
}
The above program would not compile because the compiler does not understand what
Discount is being referred to in the second Discount call: is it
InterestAndDiscount::Discount or BuyAndSell::Discount?
If you want to use different namespaces with the using namespace routine, each
namespace will have to control its scope. One solution would be to create a “physical”
scope for each namespace. Here is an example:
#include <iostream.h>
namespace InterestAndDiscount
© FunctionX, Inc. 25
C++ Fundamentals Chapter 3 Techniques of Using Variables
{
...
}
namespace BuyAndSell
{
...
}
int main()
{
{
using namespace InterestAndDiscount;
...
return 0;
}
Before creating a “physical” scope, we saw that the compiler is able to point out what
problem occurred at compilation time. Fortunately, the compiler is able to explicitly
designate what problem it encountered. In this case there is a conflict in name resolution:
two namespaces have a member of the same name.
The solution, which is commonly used, is to qualify the variable that is causing the
conflict. You can qualify only the second Discount call because the compiler will
associtate the first Discount call with the first using namespace. The safest way is to
qualify both calls to the Discount variable, as follows:
#include <iostream.h>
namespace InterestAndDiscount
{
...
}
namespace BuyAndSell
{
...
}
int main()
{
using namespace InterestAndDiscount;
Principal = 12500; // $
Rate = 8.25; // %
Time = 5; // Years
© FunctionX, Inc. 26
C++ Fundamentals Chapter 3 Techniques of Using Variables
return 0;
}
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
{
long ItemNumber;
bool QualifyForDiscount;
}
}
To access a member of a nested namespace, first call its parent, type the :: operator, type
the name of the nested namespace, followed by the :: operator, then type the name of the
variable you are trying to access. Here is an example:
© FunctionX, Inc. 27
C++ Fundamentals Chapter 3 Techniques of Using Variables
#include <iostream.h>
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
}
}
int main()
{
BuyAndSell::OriginalPrice = 780.50;
BuyAndSell::TaxRate = 7.55;
BuyAndSell::Discount = 25; // %
BuyAndSell::ItemID::ItemNumber = 641238;
BuyAndSell::ItemID::QualifyForDiscount = true;
BuyAndSell::TaxAmount = BuyAndSell::OriginalPrice *
BuyAndSell::TaxRate / 100;
BuyAndSell::DiscountAmount = BuyAndSell::OriginalPrice *
BuyAndSell::Discount / 100;
BuyAndSell::NetPrice = BuyAndSell::OriginalPrice +
BuyAndSell::TaxAmount -
BuyAndSell::DiscountAmount;
return 0;
}
Following the same logic, you can have as many namespaces and as many nested
namespaces in your application as you desire. If you nest a namespace, you can use as
many :: operators to qualify each member of the nested namespace you want. Here is an
example:
#include <iostream.h>
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
© FunctionX, Inc. 28
C++ Fundamentals Chapter 3 Techniques of Using Variables
double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
namespace DateSold
{
int Month;
int Day;
int Year;
}
}
}
int main()
{
...
BuyAndSell::ItemID::DateSold::Month = 10;
BuyAndSell::ItemID::DateSold::Day = 18;
BuyAndSell::ItemID::DateSold::Year = 2002;
...
return 0;
}
You can also use the using namespace routine by calling each namespace using its
complete name:
#include <iostream.h>
namespace BuyAndSell
{
double OriginalPrice;
double TaxRate;
double TaxAmount;
double Discount;
double DiscountAmount;
double NetPrice;
namespace ItemID
{
long ItemNumber;
bool QualifyForDiscount;
namespace DateSold
{
int Month;
int Day;
int Year;
}
}
}
int main()
{
using namespace BuyAndSell;
using namespace BuyAndSell::ItemID;
© FunctionX, Inc. 29
C++ Fundamentals Chapter 3 Techniques of Using Variables
OriginalPrice = 780.50;
TaxRate = 7.55;
Discount = 25; // %
ItemNumber = 641238;
QualifyForDiscount = true;
return 0;
}
Otherwise, you can create a using namespace for each namespace and make sure that
each one of them controls its scope. As long as you are using the scope access operator to
identify the variable that is being accessed inside of a using namespace, you can call the
member of any namespace in any scope, provided you qualify it.
© FunctionX, Inc. 30
C++ Fundamentals Chapter 3 Techniques of Using Variables
The following additional libraries can be used to include C header files into a C++
program:
Therefore, whenever you need to use a library that is part of the std namespace, instead
of typing a library with its file extension, as in iostream.h, you can just type the name of
the library as in iostream. Then, on the second line, type using namespace std;
#include <iostream.h>
#include <iostream>
using namespace std;
Because this second technique is conform with the C++ Standard, we will use it
whenever we need one of its libraries.
The C++ Standard recommends that no function be provided without a returning value.
For example, although we would bew allowed to define the main() function as in
#include <iostream>
using namespace std;
main() {}
you should define what kind of value main() would return. Therefore, the main()
function should be written as int main() {}
As we will learn when studying functions, when a function has been written with int, it
must provide a result of a natural integer. To do this, in the last line of the body of
main(), you can type return 0;. Therefore, until we study functions, we will write the
main() function at least as follows:
#include <iostream>
using namespace std;
int main() { return 0; }
To use a string in your program, first include the string library using the using
namespace std; . In your program, declare a variable starting with the word string
followed by a valid name for the variable. Here are examples:
© FunctionX, Inc. 31
C++ Fundamentals Chapter 3 Techniques of Using Variables
string Continent;
string Company;
When requesting its value from the user, by default, the string data type 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 << "\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:
Another technique involves using parentheses following the name of the string variable,
and including the string in double-quotes. Here is an example:
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 syntax:
getline(cin, StringName);
Inside of the parentheses, the word cin informs the compiler that the request will come
from an external source, ma inly 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;
© FunctionX, Inc. 32
C++ Fundamentals Chapter 3 Techniques of Using Variables
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
The following example uses the = symbol as the end character of the sentence:
string Address;
Here is an example:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string FirstName, LastName;
return 0;
}
When requesting a string made of various words, such as an address, you can use the
getline() function as follows:
#include <iostream>
#include <string>
using namespace std;
int main()
© FunctionX, Inc. 33
C++ Fundamentals Chapter 3 Techniques of Using Variables
{
string FirstName, LastName;
string Address;
string JobPerformed;
return 0;
}
#include <iostream>
using namespace std;
namespace Students
{
string FirstName;
string LastName;
char Gender;
}
int main()
{
Students::FirstName = "Laurentine";
Students::LastName = "Sachs";
Students::Gender = 'F';
return 0;
}
© FunctionX, Inc. 34
C++ Fundamentals Chapter 3 Techniques of Using Variables
Student Registration
Full Name: Laurentine Sachs
Gender: F
© FunctionX, Inc. 35
C++ Fundamentals Chapter 9: Constructing Expressions
Chapter 8:
Constructing Expressions
? Combining Statements
© FunctionX, Inc. 36
C++ Fundamentals Chapter 9: Constructing Expressions
1.1.1 Introduction
There are techniques you can use to combine conditional statements when one of them
cannot fully implement the desired behavior.
To continue with our ergonomic program, imagine that you would really like the user to
sit down and your program would continue only once she answers that she is sitting
down, you can use the do…while statement to wait for the user to sit down; but as the
do…while is checking the condition, you can insert an if statement to enforce your
request. Here is an example of how you can do it:
#include <iostream>
using namespace std;
int main()
{
char SittingDown;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;
return 0;
}
© FunctionX, Inc. 37
C++ Fundamentals Chapter 9: Constructing Expressions
Wonderful!!!
One of the reasons you would need to nest conditions is because one would lead to
another. Sometimes, before checking one condition, another primary condition would
have to be met. The ergonomic program we have been simulating so far is asking the user
whether she is sitting down. Once the user is sitting down, you would write an exercise
she would perform. Depending on her strength, at a certain time, one user will be tired
and want to stop while for the same amount of previous exercises, another user would
like to continue. Before continuing with a subsequent exercise, you may want to check
whether the user would like to continue. Of course, this would be easily done with:
#include <iostream>
using namespace std;
int main()
{
char SittingDown;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;
char WantToContinue;
return 0;
}
If the user answers No, you can stop the program. If she answers Yes, you would need to
continue the program with another exercise. Because the user answered Yes, the
subsequent exercise would be included in the previous condition because it does not
apply for a user who wants to stop. In this case, one “if” could be inserted inside of
another. Here is an example:
#include <iostream>
using namespace std;
int main()
{
char SittingDown;
do {
cout << "Are you sitting down now(y/n)? ";
© FunctionX, Inc. 38
C++ Fundamentals Chapter 9: Constructing Expressions
char WantToContinue;
if(WantToContinue == '1')
{
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;
if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
else
cout << "\nWe had enough today";
return 0;
}
In the same way, you can nest statements as you see fit. The goal is to provide an
efficient and friendly application. You can insert and nest statements that provide
valuable feedback to the user while minimizing boredom. The above version of the
program can be improved as followed:
#include <iostream>
using namespace std;
int main()
{
char SittingDown;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;
© FunctionX, Inc. 39
C++ Fundamentals Chapter 9: Constructing Expressions
char WantToContinue;
if(WantToContinue == '1')
{
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;
if(LayOnBack == '0')
{
char Ready;
do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
}while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
else
cout << "\nWe had enough today";
return 0;
}
int main()
{
char Light;
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
© FunctionX, Inc. 40
C++ Fundamentals Chapter 9: Constructing Expressions
}
else if( Light == 'y' )
{
cout << "\nYellow Light";
cout << "\nBe careful!\n";
}
else if( Light == 'r' )
{
cout << "\nShow respect for the red light";
cout << "\nPlease Stop!!!\n";
}
else
cout << endl << Light << " is not a valid color.\n";
} while( Light == 'r' );
return 0;
}
2. Test the program and return to your development environment
3. To add a while and a for loops, change the program as follows:
#include <iostream>
using namespace std;
int main()
{
char Light;
int Timer;
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}
© FunctionX, Inc. 41
C++ Fundamentals Chapter 9: Constructing Expressions
if( Timer % 10 == 0 )
cout << endl;
}
cout << "\n - Red light ended -\n\n";
}
else
cout << endl << Light << " is not a valid color.\n";
return 0;
}
4. Test the program and return to development environment.
5. Save your project
break;
Although made of only one word, the break statement is a complete statement; therefore,
it can (and should always) stay on its own line (this makes the program easy to read).
The break statement applies to the most previous conditional statement to it; provided
that previous statement is applicable.
The following program would display the letter d continuously unless something or
somebody stops it. A break statement is inserted to stop this ever looping process:
#include <iostream>
using namespace std;
int main()
{
char Letter = 'd';
return 0;
}
The break statement can also be used in a do…while or a for loop the same way.
© FunctionX, Inc. 42
C++ Fundamentals Chapter 9: Constructing Expressions
The break statement is typically used to handle the cases in a switch statement. We saw
earlier that all cases in a switch would execute starting where a valid statement is found.
Consider the program we used earlier to request a number from 1 to 3, a better version
that involves a break in each case would allow the switch to stop once the right case is
found. Here is a new version of that program:
#include <iostream>
using namespace std;
int main()
{
int Number;
switch (Number)
{
case 1:
cout << "\nYou typed 1.";
break;
case 2:
cout << "\nYou typed 2.";
break;
case 3:
cout << "\nYou typed 3.";
break;
default:
cout << endl << Number << " is out of the requested range.";
}
return 0;
}
Even when using the break statement, the switch allows many case to execute as one. To
do this, as we saw when not using the break, type two cases together. This technique is
useful when validating letters because the letters could be in uppercase or lowercase. This
illustrated in the following program:
#include <iostream>
using namespace std;
int main()
{
char Letter;
switch( Letter )
{
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
© FunctionX, Inc. 43
C++ Fundamentals Chapter 9: Constructing Expressions
case 'o':
case 'O':
case 'u':
case 'U':
cout << "The letter you typed, " << Letter << ", is a vowel\n";
break;
default:
cout << "The symbol " << Letter
<< " is not an alphabetical letter\n";
}
return 0;
}
The switch statement is also used with an enumerator that controls cases. This is also a
good place to use the break statement to decide which case applies. An advantage of
using an enumerator is its ability to be more explicit than a regular integer.
To use an enumerator, define it and list each one of its members for the case that applies.
Remember that, by default, the members of an enumerator are counted with the first
member having a value of 0, the second is 1, etc. Here is an example of a switch
statement that uses an enumerator.
#include <iostream>
using namespace std;
int main()
{
int EmplStatus;
switch( EmplStatus )
{
case esFullTime:
cout << "Employment Status: Full Time\n";
cout << "Employee's Benefits: Medical Insurance\n"
<< " Sick Leave\n"
© FunctionX, Inc. 44
C++ Fundamentals Chapter 9: Constructing Expressions
case esPartTime:
cout << "Employment Status: Part Time\n";
cout << "Employee's Benefits: Sick Leave \n"
<< " Maternal Leave\n";
break;
case esContractor:
cout << "Employment Status: Contractor\n";
cout << "Employee's Benefits: None\n";
break;
case esNS:
cout << "Employment Status: Other\n";
cout << "Status Not Specified\n";
break;
default:
cout << "Unknown Status\n";
}
return 0;
}
int main()
{
char Light;
switch( Light )
{
case 'g':
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;
case 'y':
cout << "\nBe careful!\n";
break;
case 'r':
cout << "\nPlease Stop!!!\n";
break;
© FunctionX, Inc. 45
C++ Fundamentals Chapter 9: Constructing Expressions
default:
cout << endl << Light << " is not a valid color.\n";
}
return 0;
}
4. Test the program and return to development environment.
5. Assuming the user might enter a color in uppercase, change the program as follows:
#include <iostream>
using namespace std;
int main()
{
char Light;
switch( Light )
{
case 'g':
case 'G':
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;
case 'y':
case 'Y':
cout << "\nBe careful!\n";
break;
case 'r':
case 'R':
cout << "\nPlease Stop!!!\n";
break;
default:
cout << endl << Light << " is not a valid color.\n";
}
return 0;
}
6. Test the program and return to your development environment.
7. To use an enumerator in a switch statement, change the program as follows:
#include <iostream>
using namespace std;
int main()
{
int Light;
© FunctionX, Inc. 46
C++ Fundamentals Chapter 9: Constructing Expressions
switch( Light )
{
case tlGreen:
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
break;
case tlYellow:
cout << "\nYellow Light";
cout << "\nBe careful!\n";
break;
case tlRed:
cout << "\nRespect the red light";
cout << "\nPlease Stop!!!\n";
break;
default:
cout << endl << Light << " is not a valid color.\n";
}
return 0;
}
8. Test the program and return to your programming environment.
continue;
When processing a loop, if the statement finds a false value, you can use the continue
statement inside of a while, do…while or a for conditional statements to ignore the
subsequent statement or to jump from a false Boolean value to the subsequent valid
value, unlike the break statement that would exit the loop. Like the break statement, the
continue keyword applies to the most previous conditional statement and should stay on
its own line.
The following programs asks the user to type 4 positive numbers and calculates the sum
of the numbers by considering only the positive ones. If the user types a negative number,
the program manages to ignore the numbers that do not fit in the specified category:
#include <iostream>
using namespace std;
int main()
{
// Declare necessary variables
int posNumber, Sum = 0;
© FunctionX, Inc. 47
C++ Fundamentals Chapter 9: Constructing Expressions
return 0;
}
In order to use the goto statement, insert a name on a particular section of your function
so you can refer to that name. The name, also called a label, is made of one word and
follows the rules we have learned about C++ names (the name can be anything), then
followed by a colon. The following program uses a for loop to count from 0 to 12, but
when it encounters 5, it jumps to a designated section of the program:
#include <iostream>
using namespace std;
int main()
{
cout << "We need to count from 0 to 12\n";
for(int Count = 0; Count <= 12; ++Count)
{
cout << "Count " << Count << endl;
if( Count == 5 )
goto MamaMia;
}
MamaMia:
cout << "Stopped at 5";
return 0;
}
© FunctionX, Inc. 48
C++ Fundamentals Chapter 9: Constructing Expressions
can produce a true condition, as long as one of them is true. This is done with logical
conjunction or disjunction.
As you may realize already, in Boolean algebra, the result of performing a comparison
depends on how the Condition is formulated. If the driver is approaching a light that he is
expecting to display any color other than green, he would start from a statement such as
"The light is not green". If the light IS NOT green, the expression "The light is not
green" is true (very important). This is illustrated in the following table:
The "The light is not green" statement is expressed in Boolean algebra as “Not the light is
green”. Instead of writing “Not the light is green", in C++, using the logical Not operator
, you would formulate the statement as, !"The light is green". Therefore, if P means “The
light is green”, you can express the negativity of P as !P. The Boolean table produced is:
Boolean
Color Statement Symbol
Value
When a statement is true, its Boolean value is equivalent to a non-zero integer such as 1.
Otherwise, if a statement produces a false result, it is given a 0 value. Therefore, our table
would be:
Boolean Integer
Color Statement
Value Value
© FunctionX, Inc. 49
C++ Fundamentals Chapter 9: Constructing Expressions
Even though a program usually asks a straightforward question, the compiler would only
consider the expression that needs to be evaluated; that is, the expression included
between the parentheses of the if Condition. Suppose you are writing an ergonomic
program that would guide the user on when and how to exercise. One of the questions
your program would ask might be: "Are you sitting down?" There are three classic
variances to this issue: the user might be sitting down, standing up, or laying down. Your
program might look like this:
#include <iostream>
using namespace std;
int main()
{
int Position;
if( Position == 1 )
cout << "\nNow, position your back as vertically as you can.\n";
return 0;
}
That program allows the user to give one of three answers; and you might do something
depending on the user’s answer. Now, suppose you only want to know whether the user
is sitting down; in fact, the program might expect the user to be sitting down for the
subsequent assignment. Such a program could be:
#include <iostream>
using namespace std;
int main()
{
int SittingDown;
if( SittingDown == 1 )
cout << "\nGood, now we will continue with the next exercise.";
return 0;
}
If the user is standing up, you would like her to sit down. If she is laying down, you still
would like her to sit down. Based on this requirement, you might want to check whether
© FunctionX, Inc. 50
C++ Fundamentals Chapter 9: Constructing Expressions
the user is sitting down and you would not be interested in another position. The question
could then be, “Aren't you sitting down?”. In Boolean algebra, the question would be
asked as, " Are you NOT sitting down?". A better C++ question would be, “Not “ “Are
you sitting down?”. In other words, the statement (in this case the question) would be the
negation of the regular question. If P represents the “Are you sitting down?” question, the
negativity of P is expressed as !P. The new version of our program would be more
concerned with the position the user has. Since the user is expected to type 1 for Yes, the
program would display a concern for any other answer; in short, it would check the
negativity of the Condition:
#include <iostream>
using namespace std;
int main()
{
int SittingDown;
if( !(SittingDown == 1) )
cout << "\nCould you please sit down for the next exercise?";
return 0;
}
int main()
{
char Light;
if ( !(Light == 'g') )
{
cout << "\nThe light is not green";
cout << "\nPlease stop and wait.";
}
else
cout << "\nThe road is cleared. You can drive through";
return 0;
}
4. Test your program.
© FunctionX, Inc. 51
C++ Fundamentals Chapter 9: Constructing Expressions
Let’s segment these expressions and give each a name. The first statement will be called
L. Therefore,
Whenever the traffic light is red, the “The traffic light is red” statement is true. Whenever
a driver is driving, the “The driver is driving” statement is true, which means D is true.
Whenever the law is broken, the “The law is broken” statement is true. When a statement
is true, it receives a Boolean value of true:
L B D
true true true
These three statements are completely independent when each is stated in its own
sentence. The third bears any consideration only when the first two are combined.
Therefore, the third statement is a consequence or a result. The fact that a driver is
driving and/or a light is red or dis plays any color, does not make a law broken. The law is
broken only when or IF a driver drives through a red light. This means L and D have to
be combined to produce B.
A combination of the first two statements means you need Statement1 AND Statement2.
Co mbining Statement1 AND Statement2 means L AND D that produces
"The traffic light is red” AND “The driver is driving through the light"
In C++, the AND keyword is called an operator because it applies for one or more
variable. The AND operator is specifically called a binary operator because it is used on
two variables. The AND operator is used to concatenate or add two statements or
expressions. It is represented by &&. Therefore, a concatenation of L and D would be
written as L && D. Logically, what does the combination mean?
When the traffic light is red, L is true. If a driver is driving through the light, D is true. If
the driver is driving through the light that is red, this means L && D. Then the law is
broken:
© FunctionX, Inc. 52
C++ Fundamentals Chapter 9: Constructing Expressions
L D L && D B
true true true TRUE
When the traffic light is not red, regardless of the light’s color, L is false. If a driver
drives through it, no law is broken. Remember, not only should you drive through a green
light, but also you are allowed to drive through a yellow light. Therefore, B is false:
L D L && D B
false true false FALSE
If the traffic light is red, L is true. If no driver drives through it, D is false, and no law is
broken. When no law is broken, B, which is the result of L && D, is false:
L D L && D B
true false false FALSE
If the light is not red, L is false. If no driver drives through it, D is false. Consequently,
no law is broken. B, which is the result of L && D, is still false:
L D L && D B
false false false FALSE
From our tables, the law is broken only when the light is red AND a driver drives through
it. This produces:
L D L && D B
true true true TRUE
false true false FALSE
true false false FALSE
false false false FALSE
The logical conjunction operator && is used to check that the combination of two
statements results in a true condition. This is used when one condition cannot satisfy the
intended result. Consider a pizza application whose valid sizes are 1 for small, 2 for
medium, 3 for large, and 4 for jumbo. When a clerk uses this application, you would
usually want to make sure that only a valid size is selected to process an order. After the
clerk has selected a size, you can use a logical conjunction to validate the range of the
item’s size. Such a program could be written (or started) as follows:
#include <iostream>
using namespace std;
int main()
{
int PizzaSize;
© FunctionX, Inc. 53
C++ Fundamentals Chapter 9: Constructing Expressions
cout << "\nGood Choice. Now we will proceed with the toppings";
else
cout << "\nInvalid Choice";
return 0;
}
When a program asks a question to the user who must answer by typing a letter, there is a
chance that the user would type the answer in uppercase or lowercase. Since we know
that C++ is case-sensitive, you can use a combined conditional statement to find out what
answer or letter the user would have typed.
We saw that the truthfulness of a statement depends on how the statement is structured.
In some and various cases, instead of checking that a statement is true, you can validate
only negative values. This can be done on single or combined statements. For example, if
a program is asking a question that requires a Yes or No answer, you can make sure the
program gets a valid answer before continuing. Once again, you can use a logical
conjunction to test the valild answers. Here is an example:
#include <iostream>
using namespace std;
int main()
{
char SittingDown;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> SittingDown;
return 0;
}
If a police officer saw the driver breaking the law, the “A police officer saw the driver”
statement is true. Consequently, S is true.
If a (specially installed) camera took the picture (of the scene), the “A camera took the
picture of the action” statement is true. This means H is true.
© FunctionX, Inc. 54
C++ Fundamentals Chapter 9: Constructing Expressions
If the driver gets a ticket, the “The driver gets a ticket” statement is true, which means T
is true:
S H T
true true true
Once again, the third statement has no bearing unless you consider the first two. Last
time, we saw that if the first two statements were combined, only then the result would
produce the third statement. Let’s consider in which case the driver would get a ticket.
If a police officer saw the driver, would he get a ticket? Yes, because on many traffic
lights there is no camera but a police officer has authority to hand an infraction. This
means if S is true, then T also is true. This produces:
S H T
true Don't Care true
Imagine a traffic light is equipped with a camera. If the driver breaks the law, the camera
would take a picture, which means the driver would get a ticket. Therefore, if a camera
takes a picture (H is true), the driver gets a ticket (T is true):
S H T
Don't Care true true
What if a police officer catches the action and a camera takes a picture. This means the
driver will still get a ticket, even if one of both the police officer and the camera does not
act but the other does. If both the police officer and the camera catch the action and act
accordingly, the driver would get only one ticket (even if the driver receives two tickets,
only one would be considered). Therefore, whether the first statement OR the second
statement is true, the resulting third statement T is still true:
S H T
true true true
The only time the driver would not get a ticket is when no police officer catches him and
no camera takes a picture. In other words, only when both of the first two statements are
false can the third statement be false.
Since T is the result of S and H combined, we have seen that T is true whenever either S
is true OR H is true. The OR logical disjunction is expressed in C++ with the || operator.
Here is the resulting table:
S H S || H T
true true true TRUE
false true true TRUE
true false true TRUE
false false false FALSE
Consider a program that asks a question and expects a yes or no answer in the form of y
or n. Besides y for yes, you can also allow the user to type Y as a valid yes. To do this,
you would let the compiler check that either y or Y was typed. In the same way, either n
© FunctionX, Inc. 55
C++ Fundamentals Chapter 9: Constructing Expressions
or N would be valid negations. Any of the other characters would fall outside the valid
characters. Our hot-tempered program can be restructured as follows:
#include <iostream>
using namespace std;
int main()
{
char Answer;
cout << "Do you consider yourself a hot -tempered individual(y=Yes/n=No)? ";
cin >> Answer;
return 0;
}
int main()
{
char Light, L;
int Timer;
// Make sure the user enters a valid letter for a traffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
} while( Light != 'r' && Light != 'R' &&
Light != 'y' && Light != 'Y' &&
Light != 'g' && Light != 'G' );
© FunctionX, Inc. 56
C++ Fundamentals Chapter 9: Constructing Expressions
while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}
if( Timer % 10 == 0 )
cout << endl;
}
return 0;
}
4. Test the program and return to your programming environment
5. To further refine your application, change the program as follows:
#include <iostream>
using namespace std;
int main()
{
char Light;
int Timer;
int Answer;
do {
// Make sure the user enters a valid letter for a traffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
// The user typed an invalid color for the traffic light
if( Light != 'r' && Light != 'R' &&
Light != 'y' && Light != 'Y' &&
Light != 'g' && Light != 'G' )
cout << "Invalid color\n";
} while( Light != 'r' && Light != 'R' &&
© FunctionX, Inc. 57
C++ Fundamentals Chapter 9: Constructing Expressions
return 0;
}
6. Test the program and return to your development environment.
7. Save your program.
© FunctionX, Inc. 58
C++ Fundamentals Chapter 9: Constructing Expressions
The ergonomic program we have been writing so far needs to check different things
including answers from the user in order to proceed. These various assignments can be
given to functions that would simply hand the results to the main() function that can, in
turn, send these results to other functions for further processing. Here is an example:
#include <iostream>
using namespace std;
#define Or ||
#define And &&
char GetPosition()
{
char Position;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;
return Position;
}
int main()
{
char Position;
Position = GetPosition();
if( Position == 'n' Or Position == 'N' )
cout << "\nCould you please sit down for the next exercise?\n";
else
cout << "\nWonderful!!!\n\n";
return 0;
}
© FunctionX, Inc. 59
C++ Fundamentals Chapter 9: Constructing Expressions
#include <iostream>
using namespace std;
#define Or ||
#define And &&
char GetPosition()
{
char Position;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;
return Position;
}
void NextExercise()
{
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;
if(LayOnBack == '0')
{
char Ready;
do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
}while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
int main()
{
char Position, WantToContinue;
Position = GetPosition();
© FunctionX, Inc. 60
C++ Fundamentals Chapter 9: Constructing Expressions
else
{
cout << "\nWonderful!\nNow we will continue today's exercise...\n";
cout << "\n...\n\nEnd of exercise\n";
}
return 0;
}
#define OR ||
#define AND &&
char CurrentLight()
{
char Light;
// Make sure the user enters a valid letter for a t raffic light
do {
cout << "What is the current light "
<< "color(g=Green/y=Yellow/r=Red)? ";
cin >> Light;
return Light;
}
© FunctionX, Inc. 61
C++ Fundamentals Chapter 9: Constructing Expressions
void GreenLight()
{
cout << "\nThe light is green";
cout << "\nYou can proceed and drive through.\n";
}
void YellowLight()
{
int Timer = 0;
while(Timer < 5)
{
cout << Timer << ". Yellow Light - Be Careful!\n";
Timer++;
}
void RedLight()
{
int Timer;
if( Timer % 10 == 0 )
cout << endl;
}
char AreYouStillOnTheRoad()
{
char Ans;
return Ans;
}
int main()
{
char Light;
int Timer;
char Answer;
do {
Light = CurrentLight();
© FunctionX, Inc. 62
C++ Fundamentals Chapter 9: Constructing Expressions
Answer = AreYouStillOnTheRoad();
cout << endl;
} while((Answer == '1') OR (Answer == 'y') OR (Answer == 'Y') );
return 0;
}
4. Test the program and return to development environment
5. Save your project.
#include <iostream>
using namespace std;
bool GetAnswer()
{
char Ans; string Response;
cout << "Do you consider yourself a hot -tempered individual(y=Yes/n=No)? ";
cin >> Ans;
int main()
{
bool Answer;
© FunctionX, Inc. 63
C++ Fundamentals Chapter 9: Constructing Expressions
Answer = GetAnswer();
return 0;
}
#include <iostream>
using namespace std;
#define Or ||
#define And &&
string GetPosition()
{
char Position;
int main()
{
string Answer;
Answer = GetPosition();
cout << "\nAnswer = " << Answer;
return 0;
}
On paper, the function looks fine. If the user answers with y or Y, the function returns the
string Yes. If the user answer with n or N, the function returns the string No.
Unfortunately, this function has a problem: what if there is an answer that does not fit
those we are expecting? In reality the values that we have returned in the function
conform only to the conditional statements and not to the function. Remember that in
if(Condidion)Statement;, the Statement executes only if the Condition is true. Here is
what will happen. If the user answers y or Y, the function returns Yes and stops; fine, it
has returned something, we are happy. If the user answers n or N, the function returns
No, which also is a valid value: wonderful. If the user enters another value (other than y,
Y, n, or N), the execution of the function will not execute any of the return statements
and will not exit. This means that the execution will reach the closing curly bracket
without encountering a return value. Therefore, the compiler will issue a warning.
Although the warning looks like not a big deal, you should take care of it: never neglect
© FunctionX, Inc. 64
C++ Fundamentals Chapter 9: Constructing Expressions
warnings. The solution is to provide a return value so that, if the execution reaches the
end of the function, it would still return something. Here is a solution to the problem:
string GetPosition()
{
char Position;
This is illustrated in the following program that has two functions with conditional
returns:
#include <iostream>
using namespace std;
#define Or ||
#define And &&
char GetPosition()
{
char Position;
do {
cout << "Are you sitting down now(y/n)? ";
cin >> Position;
© FunctionX, Inc. 65
C++ Fundamentals Chapter 9: Constructing Expressions
void NextExercise()
{
char LayOnBack;
cout << "Good. For the next exercise, you should lay on your back";
cout << "\nAre you laying on your back(1=Yes/0=No)? ";
cin >> LayOnBack;
if(LayOnBack == '0')
{
char Ready;
do {
cout << "Please lay on your back";
cout << "\nAre you ready(1=Yes/0=No)? ";
cin >> Ready;
} while(Ready == '0');
}
else if(LayOnBack == '1')
cout << "\nGreat.\nNow we will start the next exercise.";
else
cout << "\nWell, it looks like you are getting tired...";
}
int main()
{
char Position, WantToContinue;
bool SittingDown;
Position = GetPosition();
SittingDown = ValidatePosition(Position);
© FunctionX, Inc. 66
C++ Fundamentals Chapter 9: Constructing Expressions
NextExercise();
else if( WantToContinue == '0' )
cout << "\nWell, it looks like you are getting tired...";
else
{
cout << "\nConsidering your invalid answer...";
cout << "\nWe had enough today";
}
return 0;
}
#define OR ||
#define AND &&
char CurrentLight()
{
...
}
void GreenLight()
{
...
}
void YellowLight()
{
...
}
void RedLight()
{
...
}
bool AreYouStillOnTheRoad()
{
int Ans;
if( Ans == 0 )
return false;
else if( Ans == 1 )
return true;
© FunctionX, Inc. 67
C++ Fundamentals Chapter 9: Constructing Expressions
int main()
{
char Light;
int Timer;
int Answer;
do {
Light = CurrentLight();
Answer = AreYouStillOnTheRoad();
cout << endl;
} while(Answer == 1);
#define OR ||
#define AND &&
TTrafficColor CurrentLight()
{
char Light;
© FunctionX, Inc. 68
C++ Fundamentals Chapter 9: Constructing Expressions
return tcNoColor;
}
void GreenLight()
{
...
}
void YellowLight()
{
...
}
void RedLight()
{
...
}
bool AreYouStillOnTheRoad()
{
...
}
int main()
{
TTrafficColor Light;
int Timer;
int Answer;
do {
Light = CurrentLight();
switch( Light )
{
case tcRed:
RedLight();
break;
case tcYellow:
YellowLight();
break;
case tcGreen:
GreenLight();
break;
}
Answer = AreYouStillOnTheRoad();
cout << endl;
} while(Answer == 1);
© FunctionX, Inc. 69
C++ Fundamentals Chapter 9: Constructing Expressions
Chapter 12:
Introduction to Classes
? Classes: An Introduction
© FunctionX, Inc. 70
C++ Fundamentals Chapter 12: Introduction to Clases
Imagine a company that rent cars hires you to write a program that would help process
customers orders. A car is recognized by some characteristics such as the number of door,
the type of transmission, etc. The variables that characterize such an object could be:
long SerialNumber;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondit ion;
bool CDRom;
And the program that defines a shoe box object could be:
#include <iostream>
using namespace std;
int main ()
{
long SerialNumber = 284402;
char Make[] = "Ford";
char Model[] = "Focus";
int NumberOfDoors = 4;
int Year = 2002;
char Transmission[] = "Automatic";
bool AirCondition = true;
bool CDRom = true;
double Rate = 24.95;
© FunctionX, Inc. 71
C++ Fundamentals Chapter 12: Introduction to Clases
Car Characteristics
Car #: 284402
Make: Ford
Model: Focus
Doors: 4
Year: 2002
Transmision: Automatic
A/C: 1
CD-Rom: 1
Rate: $24.95
Unless dealing with one car, this program would be rudimentary to run for each object.
The solution is to create an object called car that groups everything that characterizes the
object.
int main()
{
string FirstName = "Bertine";
string LastName = "Lamond";
double TotalHours = 36.50;
double HourlySalary = 8.52;
double WeeklySalary = TotalHours * HourlySalary;
return 0;
}
© FunctionX, Inc. 72
C++ Fundamentals Chapter 12: Introduction to Clases
int main()
{
string FirstName;
string LastName;
double TotalHours, HourlySalary, WeeklySalary;
cout << "Enter the following pieces of information about the employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
cout << "Hours worked this week: ";
cin >> TotalHours;
cout << "Hourly Salary: $";
cin >> HourlySalary;
class TCar;
As a name that represents a group of items, a class has a body that would be used to
define the items that compose it. The body of a class starts with an opening curly bracket
"{" and ends with a closing curly bracket "}". Therefore, another way to create a class is:
© FunctionX, Inc. 73
C++ Fundamentals Chapter 12: Introduction to Clases
class ClassName{};
class ClassName {
};
or
class ClassName
{
};
Since a class is built from combining other objects, you will list each variable inside of
the body of the class. Each item that composes the class is represented as a complete
variable declared with a data type and a name. As a variable, each declaration must end
with a semi-colon.
Continuing with our TCar object, we could create it using the class as follows:
class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};
The items that compose a class are called members of the class.
#include <iostream>
using namespace std;
class Employee
{
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
int main()
{
return 0;
© FunctionX, Inc. 74
C++ Fundamentals Chapter 12: Introduction to Clases
When creating a class, you will define which items are public and which ones are private.
The items that are public are created in a section that starts with the public keyword
followed by a semi-colon. The others are in the private section. If you do not specify
these sections, all of the members of a class are considered private . For example, all of
the members of the previously defined TCar class are private.
Using the public and private sections, our TCar object can be created as:
class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
private:
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};
The public and private keywords are referenced by their access level because they
control how much access a variable allows. You can create as many public sections or as
many private sections as you want. For example, the above class could be created as:
class TCar
{
public:
long SerialNumber;
char Make;
char Model;
public:
int NumberOfDoors;
int Year;
private:
char Transmission;
bool AirCondition;
© FunctionX, Inc. 75
C++ Fundamentals Chapter 12: Introduction to Clases
bool CDRom;
public:
double Rate;
};
When creating a class with different public and private sections, all of the declared
variables under an access level keyword abide by the rules of that access level. The fact
that you use different public sections does not by any means warrant different public
levels to the variables. A variable declared as public in one public section has the same
public level of access as any other variable that is declared in another public section.
A variable that is declared in a class is called a member of the class. Once the class has
been defined, you can use it as an individual variable.
class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
TCar Rental;
When an object has been declared, you can access any of its members using the member
access operator ".". First, type the name of the object variable, followed by a period,
followed by the name of the member you want to access. For example, to access the
member NumberOfDoors of the above class, you would write:
Car.NumberOfDoors;
Using this syntax, you can display the value of a class member:
or you can request its value from the user, using the cin extractor. Here is an example:
Using the cout extractor to display the values of the object members, our program could
be as follows:
© FunctionX, Inc. 76
C++ Fundamentals Chapter 12: Introduction to Clases
#include <iostream>
using namespace std;
class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};
int main ()
{
TCar Car;
Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;
At this time, we have not learned how to use arrays in a class, we include simple char
variables. Because on this, we can transform the above program using the conditional
operator as follows:
#include <iostream>
using namespace std;
class TCar
{
public:
long SerialNumber;
char Make;
© FunctionX, Inc. 77
C++ Fundamentals Chapter 12: Introduction to Clases
char Model;
int NumberOfDoors;
int Year;
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};
int main ()
{
TCar Car;
Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;
#include <iostream>
#include <string>
using namespace std;
class TEmployee
{
...
};
int main()
© FunctionX, Inc. 78
C++ Fundamentals Chapter 12: Introduction to Clases
{
TEmployee FullTime;
FullTime.FirstName = "Chester";
FullTime.LastName = "Stanley";
FullTime.TotalHours = 42.00;
FullTime.HourlySalary = 10.63;
#include <iostream>
#include <string>
using namespace std;
class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
int main()
{
TEmployee FullTime;
cout << "Enter the following pieces of information about the employee\n";
cout << "First Name: ";
cin >> FullTime.FirstName;
cout << "Last Name: ";
cin >> FullTime.LastName;
cout << "Hours worked this week: ";
cin >> FullTime.TotalHours;
cout << "Hourly Salary: $";
© FunctionX, Inc. 79
C++ Fundamentals Chapter 12: Introduction to Clases
class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;
cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;
© FunctionX, Inc. 80
C++ Fundamentals Chapter 12: Introduction to Clases
#include <iostream>
#include <string>
using namespace std;
class TEmployee
{
public:
string FirstName;
string LastName;
© FunctionX, Inc. 81
C++ Fundamentals Chapter 12: Introduction to Clases
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
double ObtainDailyHours(string s)
{
double h;
do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);
return h;
}
int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;
cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");
© FunctionX, Inc. 82
C++ Fundamentals Chapter 12: Introduction to Clases
#include <iostream>
#include <string>
using namespace std;
class TEmployee
{
public:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
double ObtainDailyHours(string s)
{
double h;
do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);
return h;
}
© FunctionX, Inc. 83
C++ Fundamentals Chapter 12: Introduction to Clases
int main()
{
TEmployee Employee;
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun, Total;
double Hourly;
cout << "Enter the following pieces of information about this employee\n";
cout << "First Name: "; cin >> Employee.FirstName;
cout << "Last Name: "; cin >> Employee.LastName;
cout << "Hourly Salary: $"; cin >> Employee.HourlySalary;
cout << "Enter the number of hours for each day\n";
Mon = ObtainDailyHours("Monday");
Tue = ObtainDailyHours("Tuesday");
Wed = ObtainDailyHours("Wednesday");
Thu = ObtainDailyHours("Thursday");
Fri = ObtainDailyHours("Friday");
Sat = ObtainDailyHours("Saturday");
Sun = ObtainDailyHours("Sunday");
© FunctionX, Inc. 84
C++ Fundamentals Chapter 12: Introduction to Clases
14. Test the program twice to make sure it behaves appropriately. Test it once with less
than 40 hours; test it again with overtime.
15. Return to your programming environment
#include <iostream>
using namespace std;
class TCar
{
public:
...
};
int main ()
{
TCar Car;
Car.SerialNumber = 284402;
Car.Make = 'F';
Car.Model = 'F';
Car.NumberOfDoors = 4;
Car.Year = 2002;
Car.Transmission = 'A';
Car.AirCondition = true;
Car.CDRom = true;
Car.Rate = 24.95;
...
return 0;
}
You can also initialize an object as a variable. This time, type the name of the variable
followed by the assignment operator, followed by the desired values of the variables
listed between an opening and a closing curly brackets; each value is separated with a
comma. The first rule you must follow is that the list of variables must follow the order of
the declared members of the class. The second rule you must observe is that none of the
members of the class must be another class:
#include <iostream>
using namespace std;
class TCar
{
public:
long SerialNumber;
char Make;
char Model;
int NumberOfDoors;
int Year;
© FunctionX, Inc. 85
C++ Fundamentals Chapter 12: Introduction to Clases
char Transmission;
bool AirCondition;
bool CDRom;
double Rate;
};
int main ()
{
TCar Car = { 62376, 'g', 'm', 2, 1998, 'm', false, false, 19.95 };
When initializing a class that contains other classes, as we will learn when studying
composition, you cannot use the above square brackets, each class that is a member of
your object must be initialized separately.
© FunctionX, Inc. 86
C++ Fundamentals Chapter 12: Introduction to Clases
A function that is a member of a class is also called a method. Therefore, in this book, the
word “method”, when associate with a class, refers to a function that is a member of that
class.
Imagine you have a box, you know its dimensions and want to get its total
area and possibly its volume. From what we have learned so far, you can
create its class as follows:
class TBox
{
public:
double Length;
double Width;
double Height;
};
To calculate its area and volumne, you can include some member functions. Our object,
when including methods could be structured as follows:
class TBox
{
public:
double Length;
double Width;
double Height;
void TotalArea();
void Volume();
};
When using methods on a class, the variables are used to hold or store values, called data,
of the object, while methods are used to perform assignments related to the object. One
way you can control the data held by variables is to hide data from the "external world".
To achieve this, you should declare the member variables in the private section. After
doing this, use the methods in the public section to help the class interact with the other
objects or functions of the program. Based on this, our TBox object would look like this:
class TBox
{
private:
double Length;
double Width;
© FunctionX, Inc. 87
C++ Fundamentals Chapter 12: Introduction to Clases
double Height;
public:
void TotalArea();
void Volume();
};
There are at least two techniques you can use to implement a method member
classTEmployee
{
public:
void IdentifyEmployee();
void GetHourlySalary();
void CalcTotalHours();
void CalcGrossPay();
void Display();
private:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double GrossPay;
};
class TBox
{
private:
double Length;
double Width;
double Height;
public:
double TotalArea();
double Volume()
{
return Length * Width * Height;
}
};
If your class has a lot of methods, this technique could be cumbersome. You should use it
only for small methods.
© FunctionX, Inc. 88
C++ Fundamentals Chapter 12: Introduction to Clases
#include <iostream>
#include <string>
using namespace std;
class TEmployee
{
public:
void Ident ifyEmployee()
{
cout << "Identify the Employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
}
void GetHourlySalary()
{
cout << "Hourly Salary: $";
cin >> HourlySalary;
}
void CalcTotalHours()
{
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;
© FunctionX, Inc. 89
C++ Fundamentals Chapter 12: Introduction to Clases
double ObtainDailyHours(string s)
{
double h;
do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);
return h;
}
int main()
{
TEmployee Contractor;
Contractor.IdentifyEmployee();
Contractor.GetHourlySalary();
Contractor.CalcTotalHours();
Contractor.CalcGrossPay();
Contractor.Display();
© FunctionX, Inc. 90
C++ Fundamentals Chapter 12: Introduction to Clases
To implement a method outside of the class, provide the return type of the method,
followed by the class' name, followed by the scope access operator “::”, followed by the
method's name, followed by the arguments, if any, between parentheses, and finally
define what the function should do, in its body.
class TBox
{
private:
double Length;
double Width;
double Height;
public:
void TotalArea();
double Volume();
};
double TBox::Volume()
{
return Length * Width * Height;
}
#include <iostream>
#include <string>
using namespace std;
© FunctionX, Inc. 91
C++ Fundamentals Chapter 12: Introduction to Clases
class TEmployee
{
public:
void IdentifyEmployee();
void GetHourlySalary();
void CalcTotalHours();
void CalcGrossPay();
void Display();
private:
string FirstName;
string LastName;
double TotalHours;
double HourlySalary;
double WeeklySalary;
};
void TEmployee::IdentifyEmployee()
{
cout << "Identify the Employee\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
}
void TEmployee::CalcTotalHours()
{
// Hours for each day
double Mon, Tue, Wed, Thu, Fri, Sat, Sun;
void TEmployee::GetHourlySalary()
{
cout << "Hourly Salary: $";
cin >> HourlySalary;
}
void TEmployee::CalcGrossPay()
{
// If there is no overtime, return a regular salary
if( TotalHours <= 40 )
WeeklySalary = TotalHours * HourlySalary;
else // if( Hours > 40 )
{
// For an overtime period, regular hours = 40
const double RegularHours = 40.00;
© FunctionX, Inc. 92
C++ Fundamentals Chapter 12: Introduction to Clases
void TEmployee::Display()
{
cout << "Information about the employee";
cout << "\nEmployee Name: " << FirstName << " "
<< LastName;
cout << "\nWeekly Hours: " << TotalHours;
cout << "\nHourly Salary: $" << HourlySalary;
cout << "\nWeekly Salary: $" << WeeklySalary;
}
double ObtainDailyHours(string s)
{
double h;
do {
cout << s << ": ";
cin >> h;
if(h < 0 || h > 24)
cout << "Please enter a number between 0.00 and 24.00\n";
}while(h < 0 || h > 24);
return h;
}
int main()
{
TEmployee Contractor;
Contractor.IdentifyEmployee();
Contractor.GetHourlySalary();
Contractor.CalcTotalHours();
Contractor.CalcGrossPay();
Contractor.Display();
© FunctionX, Inc. 93
C++ Fundamentals Chapter 12: Introduction to Clases
To declare a class’ method as inline, precede its name with the inline keyword when
declaring the method in the class:
class TBox
{
private:
double Length;
double W idth;
double Height;
public:
inline double TotalArea();
double Volume();
};
You can choose which methods would be inline and which ones would not. When
implementing the method, you can precede the method with the inline keyword. You can
also omit the inline keyword in the class but use it when defining the method.
If you decide to implement a method locally (in the class), you have the option of
implementing it as inline:
class TBox
{
private:
double Length;
double Width;
double Height;
public:
inline double TotalArea()
{
return (2 * (Length + Width))+
(2 * (Length + Height))+
(2 * (Width+Height));
}
double Volume();
};
On the other hand, if you omit the inline keyword, the compiler would take care of it.
Normally, any function implemented in the body of the class is considered inline.
© FunctionX, Inc. 94
C++ Fundamentals Chapter 12: Introduction to Clases
class TEmployee
{
public:
...
void CalcTaxAmount()
{
if( IsMarried() == false )
TaxAmount = WeeklySalary * 30 / 100;
else
TaxAmount = WeeklySalary * 15 / 100;
private:
...
};
void TEmployee::Display()
{
CalcTaxAmount();
© FunctionX, Inc. 95
C++ Fundamentals Chapter 12: Introduction to Clases
Once an object is defined and behaves as complete as possible, the other functions or
objects of the program can make the appropriate calls trusting that the called object can
handle its assignments efficiently. This ability allows you to (tremendously) reduce the
work overload of the other components of a program.
The main() function can simply call the appropriate member of the TBox object now:
#include <iostream>
using namespace std;
class TBox
{
private:
double Length;
double Width;
double Height;
public:
void GetTheDimensions();
inline double TotalArea()
{
return (2 * (Length + W idth))+
(2 * (Length + Height))+
(2 * (Width+Height));
}
double Volume();
void BoxCharacteristics();
};
void TBox::GetTheDimensions()
{
cout << "Enter the dimensions of the box\n";
cout << "Length: "; cin >> Length;
cout << "Width: "; cin >> Width;
cout << "Height: "; cin >> Height;
}
double TBox::Volume()
{
return Length * Width * Height;
}
void TBox::BoxCharacteristics()
{
cout << "\nBox Characteristics";
cout << "\nLength: " << Length;
cout << "\nWidth: " << Width;
cout << "\nHeight: " << Height;
cout << "\nArea: " << TotalArea();
cout << "\nVolume: " << Volume();
© FunctionX, Inc. 96
C++ Fundamentals Chapter 12: Introduction to Clases
}
int main()
{
TBox Box;
Box.GetTheDimensions();
Box.BoxCharacteristics();
return 0;
}
...
void TEmployee::Display()
{
IdentifyEmployee();
GetHourlySalary();
CalcTotalHours();
CalcGrossPay();
CalcTaxAmount();
...
int main()
{
TEmployee Contractor;
Contractor.Display();
© FunctionX, Inc. 97
C++ Fundamentals Chapter 19: Combinations of Objects
Chapter 18:
Objects and their
Environment
© FunctionX, Inc. 98
C++ Fundamentals Chapter 19: Combinations of Objects
There are various techniques used to mix objects in a program. To imitate the idea of
combining different variables in a program, we will start by passing an object as a
function argument, then we will be using various objects in the same program.
18.1.1 Introduction
C++ allows you to pass an object to a function or to return an object from a function. An
object you use in a program can come from any source: an object built-in the operating
system, an object shipped with your compiler, an object that is part of the C++ language,
or one that you create.
The first thing you should do is to create an object, unless you are using an existing one.
Here is an example:
namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();
private:
double Length;
double Height;
double Width;
};
}
© FunctionX, Inc. 99
C++ Fundamentals Chapter 19: Combinations of Objects
#endif // VolumesH
The source file is used to initialize the object (its member variables) and to perform the
necessary calculations involved with the object.
#include "Volumes.h"
namespace Volumes
{
TBox::TBox(double L, double H, double W)
: Length(L), Height(H), Width(W)
{
}
TBox::~TBox()
{
}
Once the object is built, you can call it from another function. As we have done with the
main() function, you can call an object “as is” using the default constructor, which itself
has the responsibility of using initializing the values for its members:
#include <iostream>
#include "Volumes.h"
int main()
{
TBox RedBrick(6.25, 4.65, 3.85);
return 0;
}
Box Properties
Length = 6.25
Height = 4.65
Width = 3.85
Area = 142.055
Volume = 111.891
#ifndef StudentsH
#define StudentsH
#include <string>
using namespace std;
namespace Students
{
namespace Registration
{
class Student
{
public:
Student();
Student(string fn, string ln,
int DOB, int MOB, int YOB);
~Student();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
} // namespace Registration
} // namespace Students
#endif // StudentsH
#include "Students.h"
namespace Students
{
namespace Registration
{
Student::Student()
: FirstName("John"),
LastName("Doe"),
DayOfBirth(1),
MonthOfBirth(1),
YearOfBirth(1990)
{
}
Student::~Student()
{
}
} // namespace Registration
} // namespace Students
8. To prepare a test of the project, change the Main.cpp file with the following:
#include <iostream>
#include "Students.h"
int main()
{
Student DefaulStudent;
return 0;
}
#include <iostream>
#include "Students.h"
int main()
{
string FN, LN;
int Day, Month, Year;
cout << "Enter the student's information\n";
cout << "First Name: ";
cin >> FN;
cout << "Last Name: ";
cin >> LN;
cout << "Day of Birth: ";
cin >> Day;
cout << "Month of Birth: ";
cin >> Month;
cout << "Year of Birth: ";
cin >> Year;
return 0;
}
Student Information
Full Name: Gregory Ballack
Date of Birth: 22/6/1988
14. Writing values to an object allows the user to control the object. That’s why set
methods are very valuable. To provide set methods, change the header file of the
Student object as follows:
#ifndef StudentsH
#define StudentsH
#include <string>
using namespace std;
namespace Students
{
namespace Registration
{
class Student
{
public:
Student();
Student(string fn, string ln,
int DOB, int MOB, int YOB);
~Student();
private:
string FirstName;
string LastName;
int DayOfBirth;
int MonthOfBirth;
int YearOfBirth;
};
} // namespace Registration
} // namespace Students
#endif
15. To request values of the Student object, change the Main.cpp file as follows:
#include <iostream>
#include "Students.h"
int main()
{
string FN, LN;
int Day, Month, Year;
cout << "Enter the student's information\n";
cout << "First Name: ";
cin >> FN;
cout << "Last Name: ";
cin >> LN;
cout << "Day of Birth: ";
cin >> Day;
cout << "Month of Birth: ";
cin >> Month;
cout << "Year of Birth: ";
cin >> Year;
Student Typical;
Typical.setFirstName(FN);
Typical.setLastName(LN);
Typical.setDayOfBirth(Day);
Typical.setMonthOfBirth(Month);
Typical.setYearOfBirth(Year);
return 0;
}
Student Information
Full Name: Juan Gomez
Date of Birth: 2/2/1991
There are two techniques used to involve an object with a function. You can pass a
member of an object as argument to a function, or you can pass the whole object as an
argument. When passing an object as a parameter, you should be familiar with the
construction of the object, know its members and which ones you need to use.
Instead of displaying the characteristics of the box in the main() function, we can use an
external function to perform that assignment.
#include <iostream>
#include "Box.h"
int main()
{
TBox Brick(5.14, 3.28, 2.86);
ShowProperties(Brick);
return 0;
}
Even if you let the user provide the values of the class, after constructing such an object,
you can pass it to a function that would manipulate it, including displaying its
characteristics.
#include <iostream>
#include "Students.h"
int main()
{
void ShowStudent(Student Std);
string FN, LN;
int Day, Month, Year;
Student Typical;
Typical.setFirstName(FN);
Typical.setLastName(LN);
Typical.setDayOfBirth(Day);
Typical.setMonthOfBirth(Month);
Typical.setYearOfBirth(Year);
ShowStudent(Typical);
return 0;
}
Student Registration
Full Name: Joan Lucent
Date of Birth: 18/4/1986
As opposed to requesting the dimensions of the box from the main() function, we will
use an external function to take care of that so that when the object is returned, the other
functions or objects would trust that it can be used by another part of the program.
#include <iostream>
#include "Box.h"
TBox GetDimensions()
{
double L, H, W;
int main()
{
TBox Boom;
Boom = GetDimensions();
ShowProperties(Boom);
return 0;
}
Box Properties
Length = 40.12
Height = 36.06
Width = 28.82
Area = 7284.47
Volume = 41694.7
Press any key to continue
Another version of the GetDimensions() function would consist of assigning the values of
the member variables of the object to the right access methods:
TBox GetDimensions()
{
TBox B;
double L, H, W;
B.setLength(L);
B.setHeight(H);
B.setWidth(W);
return B;
}
As another technique, you can first build the object by assembling the necessary member
variables. Once the variables are gathered, you build an object based on those and return
such an object from the function. Here is an example:
TBox GetDimensions()
{
double L, H, W;
Any of these techniques should allow you to return the desired object from a function and
be able to use that object somewhere else, including displaying its properties using
another function
#include <iostream>
#include "Students.h"
Student Registration()
{
string FN, LN;
int Day, Month, Year;
Student s;
s.setFirstName(FN);
s.setLastName(LN);
s.setDayOfBirth(Day);
s.setMonthOfBirth(Month);
s.setYearOfBirth(Year);
return s;
}
int main()
{
void ShowStudent(Student Std);
Student Typical;
Typical = Registration();
ShowStudent(Typical);
return 0;
}
Student Registration
Full Name: Jarrel Jeremies
Date of Birth: 2/4/1991
To pass an object by reference, use the ampersand operator “&” between its name and the
name of the argument inside of the function’s parentheses:
#include <iostream>
#include "Box.h"
Box.setLength(L);
Box.setHeight(H);
Box.setWidth(W);
}
int main()
{
TBox Boom;
GetDimensions(Boom);
ShowProperties(Boom);
return 0;
}
Box Properties
Length = 12.44
Height = 14.66
Width = 16.88
Area = 1279.64
Volume = 3078.41
#include <iostream>
#include "Students.h"
Stud.setFirstName(FN);
Stud.setLastName(LN);
Stud.setDayOfBirth(Day);
Stud.setMonthOfBirth(Month);
Stud.setYearOfBirth(Year);
}
int main()
{
void ShowStudent(Student Std);
Student Typical;
Registration(Typical);
ShowStudent(Typical);
return 0;
}
The functions we have used so far to display the properties of our object do not modify
their arguments. For this reason, it would be safe and advantageous to pass such an object
as a constant. To pass an object as constant, type the const keyword on its left. Here is an
example:
int main()
{
void ShowStudent(const Student& Std);
Student Typical;
Registration(Typical);
ShowStudent(Typical);
return 0;
}
When defining the function, use the pointer access operator (->) to access the desired
members of the object:
Box->setDimensions(L, H, W);
}
When calling a function whose argument was passed a a pointer to an object, it depends
on how the object was declared in the function that is making the call. For example,
imagine that you declared a TBox instance regularly as we did previously:
TBox Box;
In order to pass such an object to the GetDimensions() function, call the argument as a
reference. Here is an example:
#include <iostream>
#include "Volumes.h"
Box->setLength(L);
Box->setHeight(H);
Box->setWidth(W);
}
int main()
{
TBox Box;
GetDimensions(&Box);
ShowProperties(Box);
return 0;
}
Box Properties
Length = 2.25
Height = 4.15
Width = 1.85
Area = 42.355
Volume = 17.2744
In the same way, if you pass an argument to a function that does not modify its argument,
because an argument passed as a pointer gives direct access to the address (or memory
location) of the argument, you can pass the argument as a constant pointer. Here is an
examp le:
#include <iostream>
#include "Volumes.h"
int main()
{
TBox Box;
GetDimensions(&Box);
ShowProperties(&Box);
return 0;
}
s->setFirstName(FN);
s->setLastName(LN);
s->setDayOfBirth(Day);
s->setMonthOfBirth(Month);
s->setYearOfBirth(Year);
}
int main()
{
void ShowStudent(const Student &Std);
Student Typical;
Registration(&Typical);
ShowStudent(Typical);
return 0;
}
...
2. Test the application and return to your programming environment.
3. To pass an argument as a constant pointer, change the ShowStudent() function as
follows:
#include <iostream>
#include "Students.h"
int main()
{
void ShowStudent(const Student *Std);
Student Typical;
Registration(&Typical);
ShowStudent(&Typical);
return 0;
}
ObjectName * InstanceName ;
The ObjectName is one already created. It could be in the program or one that shipped
with the compiler. Once again, the asterisk * lets the compiler know that the object is
declared as a pointer. The InstanceName follows the same rules we have applied to other
variables so far. For example, you can declare our TBox as a pointer as follows:
TBox *Box;
Just like when initializing a regular variable, you can assign an instance of a regular
object to an object’s pointer. Here is an example:
TBox Brick;
TBox *Box = &Brick;
When an object has been declared as a pointer, use the pointer access operator “->” to
access any of its available members. For example, to access the getLength() method of
the TBox object using the Box pointer, you can type:
Box->getLength();
Here is an example program that declares a pointer to a TEllipse object and uses the ->
operator to access its members:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct TEllipse
{
double Radius;
double radius;
};
int main()
{
TEllipse Els;
TEllipse* Elisp = &Els;
return 0;
}
cout << s;
cin >> r;
return r;
}
Earlier, we saw that, when calling a function that has received an argument as a pointer, it
depends on how the object was declared. If the object was declared as a pointer and
rightly initialized, since it is a pointer already, when passing it to a function, simply
provide its name. Here is an example:
#include <iostream>
#include "Volumes.h"
int main()
{
TBox Brick;
TBox *Box = &Brick;
GetDimensions(Box);
ShowProperties(Box);
return 0;
}
The object we have just declared needed a second object to be initialized. C++ allows
you to dynamically create an object and initialize it to its class using the new operator.
This can be done as follows:
int main()
{
TBox *Box = new TBox;
GetDimensions(Box);
ShowProperties(Box);
return 0;
}
With such a TBox instance so declared and initialized, you can access any of its available
members.
Once you have finished using a dynamically created object, you should get rid of it and
reclaim the memory space it was using. To delete a dynamic object, use the delete
operator. The syntax is:
delete ObjectInstance;
The delete keyword is required. The ObjectInstance is the name used when declaring the
pointer, the same name used when using the new operator. Here is an example:
int main()
{
TBox *Box = new TBox;
GetDimensions(Box);
ShowProperties(Box);
delete Box;
return 0;
}
To avoid the possibility of a memory leak, you can assign the NULL constant to the
memory space left by the deleted instance of your object:
int main()
{
TBox *Bo x = new TBox;
GetDimensions(Box);
ShowProperties(Box);
delete Box;
Box = NULL;
return 0;
}
int main()
{
void ShowStudent(const Student *Std);
Student *Typical = new Student;
Registration(Typical);
ShowStudent(Typical);
return 0;
}
int main()
{
void ShowStudent(const Student *Std);
Student *Typical = new Student;
Registration(Typical);
ShowStudent(Typical);
delete Typical;
Typical = NULL;
return 0;
}
In the same way you can find out the amount of space occupied by an instance of an
object:
int main()
{
TBox Box;
cout << "Size of TBox class: " << sizeof(TBox) << " bytes\n";
cout << "Size of Box instance: " << sizeof(Box) << " bytes\n";
return 0;
}
If the object is declared as a pointer, to get the size of a pointer to an object, use the sizeof
operator. If you use just the name of the pointer, you will get the current size of the
declared object. If you append the * operator, you will get the actual size of the object:
int main()
{
TBox *Box = new TBox;
cout << "Size of TBox class: " << sizeof(TBox) << " bytes\n";
cout << "Size of *Box instance: " << sizeof(*Box) << " bytes\n";
cout << "Size of Box instance: " << sizeof(Box) << " bytes\n";
delete Box;
Box = NULL;
return 0;
}
a function that can refer to the object itself, in the body of the class, declare a function
that holds the same name as the class, followed by a valid name of a function and the
parentheses. Here is an example:
namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();
TBox Add();
private:
double Length;
double Height;
double Width;
};
}
#endif // VolumesH
An example of using such a function would consist of changing the value of each
member of the class. Since the function is declared as returning the value of the same
variable, you can implement it as follows:
TBox TBox::Add()
{
TBox Box;
return Box;
}
Calling this self-returning function is equivalent to changing the values of the member
variables, as illustrated in the followng main() function:
#include <iostream>
#include <iomanip>
#include "Volumes.h"
int main()
{
TBox Box;
// GetDimensions(Box);
cout << "A TBox with default dimensions";
ShowProperties(&Box);
return 0;
}
Box Properties
Length = 12.52
Height = 8.95
Width = 5.75
Area = 471.01
Volume = 644.31
You can use this self-returning ability to define almost any type of method that returns
the same class. A particular function can be used to modify the default values of the
member variables. For example, you can write a method that would be passed a constant
value and ask the method to add this value to each member variable before returning the
same object that made the call. Such a method can be declared as follows:
To add the provided value to each member variable, you can define the method as
follows:
return Box;
}
The method can be tested with the following implementation of the main() function:
int main()
{
TBox Box(6.42, 2.84, 4.56);
TBox Brick = Box.Add(8.92);
ShowProperties(&Brick);
return 0;
}
Of course, as done with the addition, you can also declare a method that performs a subtr
action, or a multiplication, or a division, etc. Such a method can be passed a constant
double as done for the addition:
One way you can implement such a method is to multiply the passed constant to each
member to the calling object and return it:
Box.Length = Length * d;
Box.Height = Height * d;
Box.Width = Width * d;
return Box;
}
Another type of self-returning method you can create would consit of adding the values
of another instance of the class to the one that makes the call before returning it with new
values. Such a method would take one argument like a copy constructor: a constant
reference of the class. The method can be declared as follows:
One way you can use this method is to add each one of its values to the corresponding
member variable of the object that made the call:
return NewBox;
}
int main()
{
TBox Box(6.42, 2.84, 4.56);
ShowProperties(&Brick);
return 0;
}
namespace Volumes
{
class TBox
{
public:
TBox(double L = 0, double H = 0, double W = 0);
TBox(const TBox &Box);
~TBox();
private:
double Length;
double Height;
double Width;
};
}
#endif // VolumesH
#include "Volumes.h"
namespace Volumes
{
TBox::TBox(double L, double H, double W)
: Length(L), Height(H), Width(W)
{
}
TBox::~TBox()
{
}
Box.Length = Length + d;
Box.Height = Height + d;
Box.Width = Width + d;
return Box;
}
Box.Length = Length - d;
Box.Height = Height - d;
Box.Width = Width - d;
return Box;
}
Box.Length = Length * d;
Box.Height = Height * d;
Box.Width = Width * d;
return Box;
}
Box.Length = Length / d;
Box.Height = Height / d;
Box.Width = Width / d;
return Box;
}
}
return NewBox;
}
} // namespace Volumes
change the value of that object and return it. C++ proposes an alternative to returning an
object from one of its member functions. Instead of explicitly declaring a variable when
implementing a function that returns the same object, the compiler simply needs to know
what object you want to return: the object that called the function or a newly declared
one. If you want to return the same object, you can use a special pointer called this.
As its name implies, the this pointer is a self referencing object, which means it allows
you to designate the object that is making the call as the same object you are referring to.
Using the this pointer is a technique that allows you to perform any necessary operation
on an object without the help of an external function and return the same object.
Suppose you have a method called Add() and you want to pass it a constant value that
would be added to an object (or to the members of the object) and change the value of the
object. We saw that such a method can be declared as follows:
The problem we have with this method is that it will return a value or a copied value of
the object that calls it: the real value of the object would not be touched and cannot be
returned. This means that our goal would not be met. The solution is to return a reference
to the object that makes the call. As we saw with variables, giving access to the caller
means the caller would get the object itself, from its location or address, instead of
sending a copy of its value. Therefore, this Add() method should return a reference (or
even a pointer). Therefore, the method should be declarded as follows:
In the way, you can declare the other methods we had earlier:
namespace Volumes
{
class TBox
{
public:
...
private:
double Length;
double Height;
double Width;
};
}
#endif // VolumesH
When implementing such a method, because the method should return the same object,
you do need to declare a local variable to hold the changed variable. Since the member
variables of the object will be modified, the member function cannot be declared as a
constant. A priori, the method would be implemented as follows:
When implementing this function, the values of the variables will certainly be modified
to implement whatever behavior you want. To return the same object, the this object
must be called as a pointer, with *this. Here is the new implementation of the function:
return *this;
}
Using the same logic, you can use the this pointer to return the object from any of its
member methods that needs to reference the same object:
#include "Volumes.h"
namespace Volumes
{
...
return *this;
}
return *this;
}
return *this;
}
return *this;
}
return *this;
}
} // namespace Volumes
Appendix
Since the bits are numbered from right to left , you can calculate the decimal value of a
byte using the base 2. Consider a binary number intensely mixed with 0s and 1s such as
11010111. The 11010111 binary number can be calculated as:
1 1 0 1 0 1 1 1
= 1* 27 + 1* 26 + 0* 25 + 1* 24 + 0*23 + 1*22 + 1*21 + 1*20
= 1*128 + 1* 64 + 0* 32 + 1*16 + 0* 8 + 1*4 + 1*2 + 1*1
128 + 64 + 0 + 16 + 0 + 4 + 2 + 1
= 215
128 64 32 16 8 4 2 1
When you are presented with a binary number, you can just write the corresponding bit
value under the ranking decimal number. Consider that you want to calculate the decimal
equivalent of the 01110110 binary number. Using the Binary to Decimal Conversion
Table, you can perform the operation like this:
128 64 32 16 8 4 2 1
0 1 1 1 0 1 1 0
This produces:
0 64 32 16 0 4 2 0
= 64 + 32 + 16 + 4 + 2
= 118
Once you are presented with a binary number, you can produce or use a table inspired
from the binary to decimal conversion table:
Imagine you would like to convert the 10011110011101101 binary number to a decimal
value.
1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 0 1
65536 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1
= 81133
When all bits are 0, the byte also has a value of 0. When combining and mixing 0 and 1
bits, you can get binary values as varied as possible: 0101 0010 or 1101 1110 or 0111
1100. We only need to know what each combination would represent. If you divide bits
by groups of four, you can use the table of numeric conversions to find out what each
group represents. Consider a binary number such as 10101101. Dividing it in groups of 4-
bits, we get 1010 1101. Referring to our conversion table, the low order nibble has a
hexadecimal value of 8. The high order nibble has a hexadecimal value of C.
1010 1101
A D
To convert a binary number to hexadecimal, use the table of numeric conversions. First,
convert the number in groups of 4 bits. If the most left group has less than 4 bits,
complete the other bits with 0 each.
Since the most left group has only 2 bits, you can add two 0 bits to its left to make it a
group of 4. The number becomes:
Remember that the maximum decimal number you can store in a byte is 255. Once you
have a decimal number, you can use the remainder operation to fill out the bits. Let's
convert the number 206.
Considering 206, find out the range of the number. Since this is greater than 128, fill out
bit 7 with 1. This produces:
128 64 32 16 8 4 2 1
1
Next, find the remainder of 206 by 128. This is 206 / 128 = Remainder(78). In C++, this
operation would be 206 % 128 = 78. The result, 78, is greater than 64. Therefore, fill out
the corresponding bit of 64, which is bit 6, with 1:
128 64 32 16 8 4 2 1
1 1
128 64 32 16 8 4 2 1
1 1 0 0 1
128 64 32 16 8 4 2 1
1 1 0 0 1 1
Find the remainder of 6 by 4: 6 % 4 = 2. According to this, bit 1 will have a binary value
of 1. The remaining decimal value is 0. Therefore, bit 0 has a value of 0. The decimal
number 206 produces the following table:
128 64 32 16 8 4 2 1
1 1 0 0 1 1 1 0
= 1 1 0 0 1 1 1 0
= 11001110
= 1100 1110
Converting a decimal number to binary takes longer because of the various comparisons
you would perform. There are, as always, various techniques available. Once again, find
the range of the number using numbers such as those:
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1
Consider you would like to convert the following decimal number 408340623 =
408,340,623 to binary.
408,340,623 is less than 536,870,912 but is greater than 268,435,456. Therefore , we will
start the counting at 268,435,456. Write 1 under 268,435,456.
Now, find the remainder of 139,905,167 by 134,217,728. This is 5,687,439. This number
is between 8,388,608 and 4,194,304. Therefore, fill each bit to 0 down to 4,194,304:
Then find the remainder of 5, 687,439 by 4,194,304. This produces 1,493,135. This
number is greater than 1,048,576. Therefore, write 0 under 2,097,152 and 1 under
1,048,576.
Find the remainder of 1,493,135 by 1,048,576. The result is 444,559. The next number
greater than 444,559 is 262,144. Therefore, fill it with 1 and fill out the524,288 number
with 0:
Find the remainder of 444,559 by 262,144. This is 182415. This number is greater than
131,072. Therefore, fill out the corresponding bit with 1.
The remainder of 182,415 by 131,072 is 51343 which is less than 65,536 but greater than
32,768. For this reason, the equivalent but of 65,536 is 0 and that of 32,768 is 1:
The remainder of 51,343 by 32,768 is 18,575. This number is between 32,768 to 16,384.
This results in:
The remainder of 18,575 by 16,384 is 2191. This number is greater that 2048. Therefore,
the binary equivalents of both the 8,192 and 4,096 bits is 0. The bit equivalent of 2,048 is
1:
The remainder of 2,191 by 2,048 is 143. The next number lower than 143 is 128. The
resulting tables are:
1 1 0 0 1 0 0 0
128 64 32 16 8 4 2 1
1
Find the remainder of 143 by 128. This produces 15; a number that is greater than 8 but
less than 16. The bits of 64, 32, and 16 will receive a bit value of 0. Bit 8 will have a
value of 1:
128 64 32 16 8 4 2 1
1 0 0 0 1
128 64 32 16 8 4 2 1
1 0 0 0 1 1
128 64 32 16 8 4 2 1
1 0 0 0 1 1 1
The remainder of 3 by 2 is 1. This means, you will fill out bit 0 with 1:
128 64 32 16 8 4 2 1
1 0 0 0 1 1 1 1
This number can easily be converted from binary to hexadecimal using the table of
numeric conversions:
To convert a decimal value of a byte to its hexadecimal equivalent, again keep in mind
that the maximum number you are dealing with is 255 (this is because the operation will
be a little different later on). Find the remainder of the decimal number by 16. This
remainder will constitute the low nibble. The result will constitute the high nibble.
Therefore, use the table of numeric conversions to find the equivalent hexadecimal
number for each nibble.
As another example, Let's convert the decimal 203 to the hexadecimal system. 203 % 16
= 11 and the natural result is 12. Using the table of numeric conversions, decimal 12 =
hexadecimal C; decimal 11 = hexadecimal B. Therefore, decimal 203 = hexadecimal
0xCB
The conversion of a hexadecimal number to its binary equivalent is extremely easy; the
only thing you need is the table of numeric conversions. A byte is represented with two
hexadecimal symbols. The right symbol represents the low nibble (the first 4 bits). The
other symbol is the high nibble.
Let's convert the hexadecimal 0xD5 to binary. The binary representation of D is 1101.
The binary representation of 5 is 0101. Therefore, hexadecimal 0xD5 is represented in
binary as 11010101 or 1101 0101
Consider you would like to convert the 0x72FA to binary. Using the table of numeric
conversions:
7 = 0111
2 = 0010
F = 1111
A = 1010
161 160
Consider a hexadecimal byte represented with 0x24, to convert it to decimal, you would
use:
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111
you would see that the decimal value of hexadecimal D is 13. Therefore, the conversion
would be performed as follows:
Refering to the table of numeric conversions, you would find out that the decimal
equivalent of hexadecimal B is 11, that of E is 14, and that of A is 10. Therefore, you
would rewrite the equation as:
= 12469670 = 12,469,670
Index
_exit().....................................................................361 Backspace ................................................................ 49
Base 10 .................................................................... 41
beam.......................................................................141
++.............................................................................. 87 Bell ............................................................................ 49
+=............................................................................109 binary .....................................................................183
binary combinations.............................................. 44
< binary digit .............................................................. 43
Binary Operator....................................................667
< 184
Binary System ........................................................ 40
<<............................................................................672
bit .............................................................................. 43
<=............................................................................185
Bitwise &...............................................................110
= Bitwise AND.........................................................681
Bitwise NOT................................................110, 681
= 648 Bitwise OR...................................................111, 681
==............................................................................180 Bitwise Shift Left................................................681
> Bitwise Shift Right.............................................681
Bitwise XOR .........................................................681
> 186 Bitwise-exclusive OR..........................................112
>=...................................................................187, 667 bool ....................................................................38, 50
A Boolean.................................................................... 50
Borland ..................................................................176
Abnormal Termination........................................362 break........................................................................ 38
abort().....................................................................362 Built-in Classes
abs...........................................................................177 cin .......................................................................355
Access Level.........................................................317 Built-in Functions................................................175
acos.........................................................................176 _exit() ................................................................361
addition.................................................................... 93 abort() ................................................................362
Additive Assignment .........................................681 clrscr() ...............................................................679
Address .................................................................681 exit()...................................................................360
algebra....................................................................175 gets() ..................................................................356
Algebraic Operators ............................................103 resetiosflags()...................................................351
alphabetic Chanracters .......................................... 40 scanf()................................................................356
ampersand ............................................................... 88 setiosflags().......................................................350
AND Assignment ................................................681 system() .............................................................679
Apostrophe............................................................... 49 terminate().........................................................363
applications............................................................. 39 tolower()............................................................359
array........................................................................104 toupper()............................................................358
asin..........................................................................176 width() ...............................................................350
asm........................................................................... 38 Byte .......................................................................... 45
assignment.............................................................118
C
Assignment..........................................................681
associative............................................................... 98 C 353
atan .........................................................................176 C++ Names ............................................................. 37
atan2.......................................................................176 C++ Standard........................................................175
auto .......................................................................... 38 Calling a Function................................................119
axis ..........................................................................141 camera ....................................................................189
Carriage Return ...................................................... 49
B case.......................................................................... 38
backslash................................................................. 49 case-sensitive.......................................................... 38
ctype.h ...............................................................358 L
hex ..........................................................................348
hexadecimal .................................................348, 353 labs..........................................................................177
Hexadecimal System............................................. 41 Latin ......................................................................... 41
HI bit ........................................................................ 43 law ..........................................................................188
High Order bit ........................................................ 43 ldexp .......................................................................176
Horizontal Tab ......................................................... 49 ldiv ..........................................................................177
human.....................................................................189 Left Shift Assignment .......................................681
Left Shift Operator << ........................................113
I Length of a string.................................................342
Less Than .............................................................681
if 38, 190
if...else....................................................................194 Less Than or Equal ...........................................681
Line Feed................................................................. 49
include....................................................................410
increase.................................................................... 87 LO bit ....................................................................... 43
increment................................................................. 87 log...........................................................................176
log10.......................................................................176
index.......................................................................104
Initializer...............................................................457 Logical AND .........................................................681
Initializing a Class...............................................327 Logical NOT .........................................................681
inline ...................................................... 38, 157, 336 Logical NOT Operator........................................182
Input Operator......................................................674 Logical Operations ..............................................192
int.............................................................................. 38 Logical Operators ................................................187
integer....................................................................341 Logical OR ............................................................681
Intel........................................................................... 43 long .......................................................................... 38
interrupt.................................................................. 38 Low Order............................................................... 43
iomanip ..................................................................346 lowercase.......................................38, 307, 309, 358
ios::scientific .........................................................352 M
iostream.h ..............................................................673
isalnum()................................................................360 main ......................................................................... 38
isalpha() .................................................................359 main().....................................................................360
isascii()...................................................................360 Member Access Operator...................................318
isdigit()...................................................................359 memory .................................................................... 37
isgraph().................................................................360 method ...................................................................329
islower().................................................................359 Methods
isprint() ..................................................................360 fill() ....................................................................347
ispunct().................................................................360 put()....................................................................341
isspace().................................................................360 width() ...............................................................345
istream....................................................................674 write() ................................................................342
isupper().................................................................359 Microsoft Visual C++ .Net.................................166
isxdigit() ................................................................359 modf .......................................................................176
Modulating Assignment...................................681
K Modulus ................................................................681
Keywords ..............................................................367 Moment of Inertia ................................................141
catch...................................................................366 monitor..................................................................... 39
char.....................................................................289 Most Significant..................................................... 43
const............................................................ 67, 395 multiplication.......................................................... 98
for.......................................................................204 Multiplication .......................................................681
friend..................................................................577 Multiplicative Assignment ...............................681
namespace.........................................................429 mutable................................................................... 38
operator..............................................................647
protected............................................................602 N
public .................................................................317 namepsace.............................................................170
static...................................................................161 namespace..............................................38, 68, 344
try .......................................................................366 namespaces ...........................................................104
Negation ...............................................................681
negative.................................................................... 42
sin ...........................................................................176 V
single-quotes ........................................................... 49
sinh .........................................................................176 Vertical Tab.............................................................. 49
Size of data ..........................................................681 virtual....................................................................... 38
sizeof.......................................38, 90, 251, 342, 681 void........................................................................... 38
sound........................................................................ 49 volatile..................................................................... 38
sprintf() ..................................................................310 W
sqrt..........................................................................176
Square brackets ....................................................104 wchar........................................................................ 38
Square Brackets....................................................289 while......................................................................... 38
srand.......................................................................177 width()....................................................................350
statement................................................................190 word.......................................................................... 51
static ............................................................... 38, 161
static_cast.............................................................. 38 X
std..............................................................38, 80, 344 XOR Assignment................................................681
stdio........................................................................344
Stream Operators .................................................671
string........................................................................ 38
struct........................................................................ 38
structures ...............................................................104
Subtraction ..........................................................681
Subtractive Assignment...................................681
switch ............................................................. 38, 198
system() .................................................................679
T
tag ...........................................................................354
tan ...........................................................................176
tanh.........................................................................176
terminate() .............................................................363
this ..........................................................................521
throw ....................................................................... 38
tilde................................................................110, 488
timer .......................................................................189
tolower()................................................................359
toupper() ................................................................358
Traffic Light..........................................................188
Trailing zeros ......................................................354
Triangle ..................................................................143
trigonometry .........................................................175
true............................................................38, 40, 180
try ............................................................................. 38
Typecast ...............................................................681
typedef ..............................................................38, 65
typeid....................................................................... 38
typename ............................................................... 38
U
unary......................................................................... 86
underscore ............................................................... 38
union........................................................................ 38
unsigned ..................................................38, 42, 353
uppercase.......................................38, 307, 309, 350
using ..................................................................38, 71