Você está na página 1de 510

C++ Language

Introduction to Header Files C++ is a huge language so much that it uses various sets of instructions from different parts to do its work. Some of these instructions come in computer files that you simply "put" in your program. These instructions or files are also called libraries. To make your job easier, some of these libraries have already been written for you so that as you include them in your program, you already have a good foundation to continue your construction. Yet, some of these libraries have their limitations, which means you will expand them by writing or including your own libraries. As noted already, there are libraries previously written for you. One of them asks the computer to receive keyboard strokes from you the user (when you press a key) and another asks the machine (the computer performing some operations) to give back a result. The libraries are files that you place at the beginning of your program as if you were telling the computer to receive its preliminary instructions from another program before expanding on yours. The libraries are (also) called header files and, as computer files, they have the extension ".h". An example would be house.h, or person.h. As you see, they could have any name; when you start creating your own libraries, you will give your files custom and recognizable names. The first library we will be interested in is called iostream. It asks the computer to display stuff on the monitor's screen. To see how to put a library in your program, you put it at the beginning of the file. Here is an example:
iostream.h

To use a library in your program, you simply include it by using the word "include" before the name of the library, as follows:
include iostream.h

Since this is a computer language, the computer will follow particular instructions to perform appropriately, which will make this language distinct from the everyday languages. C++ has some words it treats specially and some that will completely depend on you the programmer. For example, the word "include" could be a special word used by C++ or a regular you want to use in your program. In this particular situation, if you want the computer to "know" that the word "include" means, "I want to include the following library", you will have to append a special sign to it. The pound sign "#" will do just that. Therefore, to include a library, you precede the include word with the # sign.

Here is an example:
#include iostream.h

There are usually two kinds of libraries or files you will use in your programs: libraries that came with C++, and those that you write. To include your own library, you would enclose it between double quotes, like this
#include "books.h"

When you include a library that came with C++, you enclose it between < and > as follows:
#include <iostream.h>

Following this same technique, you can add as many libraries as you see fit. Before adding a file, you will need to know what that file is and why you need it. This will mostly depend on your application. For example, you can include a library called stdio like this:
#include <iostream.h> #include <stdio.h>

Introduction to 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. Because C++ is so huge, its libraries are created in different namespaces, each with a particular name. To use an existing namespace in your program, you must know its name. To use such a namespace, you can type the using namespace expression followed by the name of the namespace and a semicolon. For example, to use a namespace called django, you would type:
using namespace django;

One of the namespaces used in C++ is called std. Therefore, to use it, you can type:
using namespace std;

After typing this, any part of the namespace becomes available to you. The iostream library we mentioned above is part of the std namespace. When you use it, you don't need to include the extended of the iostream file. For this reason, you can start your program with:
#include <iostream> using namespace std;

C++ Projects C++ Instructions C++ works by giving (separate) instructions to the computer. These instructions can be treated as assignments. On this site, such an assignment will be called a function. The primary function used in C++ is called main. To distinguish a function from the other types of things you will be using in your programs, a function's name is followed by an opening and a closing parentheses. For example, the main function will always be written at least as main(). When we perform a better study of functions, we will learn more about functions, their parentheses, and other related issues. When a program is written and you ask the computer to "execute" it, the first thing to look for is the main() function. This means that every C++ program should have the main() function. Because a function is an assignment, in order to perform its job, a function has a body; this is where the behavior (assignment) of the function would be "described". The body of a function starts with an opening curly bracket "{" and closes with a closing curly bracket "}". Everything in between belongs to, or is part of, the function. Therefore, the main() function can be written as:
main() {}

As we learned that we should (must) always include the libraries that we would need, our program now would include main(). Whenever you create a program, it is important to isolate any inclusion of a library on its own line. Here is an example:
#include <iostream> using namespace std; main(){}

C++ is the computer language we are going to study to write programs. C++ is a very universal language, it can be used to write programs for Linux, MS Windows, Macintosh, BeOS, Unix, etc. C++ is very powerful and can be used to create other compilers or languages, it can also be used to write an operating system. This means that you can use C++ to create/write your own computer language. You can also use C++ to create/write your own compiler; this means that, using C++, you can create your own implementation of C++, Pascal, Basic, Perl, or any other existing or non-existing language. There are many products you can use to create a program in C++. Before a program is made available, it is called a project because you are working on it. Although in the beginning you will usually be working alone, most programs involve a lot of people. That is why during the development of a program or software product, it is called a project. Each one of the available environments provides its own technique(s) of creating a C++ program or working on a C++ project. Therefore, the person who, or the company that, made the environment available to you must tell you how to use that environment (it is neither your responsibility, nor the C++ Standards job to tell you how to create a program or how to start a project). I will try to cover those that I know. The programs we will be creating on this site are called console applications. They can also be called Bash programs (especially on Unix/Linux). The technique you follow to create a project depends on the environment you are using. Executing a Program To see what your program does, you need to realize that the lines we have typed are English language

instructions asking C++ to perform the main() function. Unfortunately, the computer doesn't understand what all of this means (to a certain extent). The computer has its own language known as the machine language. So, we need to translate it in a language the computer can understand. A program was created to that effect and supplied to you with C++. This is what we call a compiler. In the past, a program used to be created from various parts all over the computer, some of the techniques are still used to "debug" a program to isolate problems or "bugs". Since this is a small program, we will just ask the computer to "execute" it and see the result. Throughout this site, the words (or verbs) "execute" and "run" will be used interchangeably to mean the same thing. The C++ language doesn't define how to create a project. When you buy or acquire a c++ compiler, its documentation should tell you how to create and execute a project. We describe here how how to create a project in most familiar environments. If you have an environment or compiler that is not in our list, consult its documentation to know how to use it. One of our most valuable goals in writing a site is to avoid including in a program an issue that has not previously been addressed or explained. This site is written as a (general) reference towards the C++ language. To learn C++, you need a C++ compiler, and we describe how to create a C++ project with some of the most commonly used compilers or programming environments. As it happens, and as you may have noticed, different companies (and different individuals for that matter) choose to implement a language as they see fit. Depending on the programming environment you are using, even depending on how you create your program (for example KDevelop, Borland C++ Builder, and Microsoft Visual C++ all provide more than one way to create or start a console application), sometimes you have a starting empty file or a file with a few lines. Whatever is in the file, you do not need to delete it. For example, KDevelop displays a commented message in the file. You should not delete that text and it will never interfere with your program. Borland C++ Builder opens a file with a couple of "#pragma" lines. You will never have any reason to delete those lines, although you can, without any risk; but since they do not affect your program, why waste your time deleting them? Depending on the programming environment you are using and how you create your program, the first file may display a line as #include <iostream.h> or another #include line. The file may also have a main() function already included. Here is how we will deal with this issue:

If the file displays a line with #include Something, leave it as is. It will not negatively affect your program. Such a file has been tested If the file displays a line with #include <iostream.h>, leave it like that and continue with our other instructions If the file is empty or it does not include a line with #include at all, then you will just follow our instructions and type them as given If the file already includes the main() function, with a line like int main(Something), use that main() function for the exercises in this book. Unless stated otherwise, that

function is ready for you and don't modify the Something part between the parentheses.

From now on, you will sometimes be asked to create a project. Follow the instructions of your compiler as we have seen above. <a href="http://c.casalemedia.com/c?s=56757&f=2&id=3538250729.8054104" target="_blank" src="http://as.casalemedia.com/s?s=56757&u=http%3A//www.functionx.com/cpp/Lesson01.htm&f=2&id=3538 width="728" height="90" border="0"></a>

Project Creation Creating and Executing a Dev-C++ 4 Application Dev-C++ is a free programming environment. To get it, you can download it from http://www.bloodshed.net. If you decide to use it, you should help the developers with a financial contribution. 1. Start Dev-C++ 4

2. On the main menu, click File -> New Project... 3. On the New Project dialog box, click the Project property sheet if necessary. Click Console Application

4. Click OK. 5. On the subsequent New Project dialog box, type Exercise to change the name of the project:

6. Click OK. You will be asked to create a location for the project. 7. Click the Create New Folder button . 8. Type Exercise1 and press Enter. 9. Double-click Exercise1 to display it in the Save In combo box:

10. Click Save. 11. Because the project has already been saved, it is better to save your C++ files as you go. As it happens, Dev-C++ has already created the first C++ file for you. Change the contents of the file as follows:

#include <iostream.h> #include <stdio.h> int main(int argc, char *argv[]) { cout << "C++ is Fun!!!"; getchar(); return 0; }

12.

13. To save the current C++ file, on the Main toolbar, click the Save button 14. Type Exo as the name of the file. 15. Click Save. 16. To execute the program, on the main menu, click Execute -> Compile

17. After the program has been compiled, click Execute.

18. After viewing the program, press Enter to close the DOS window to return to Dev-C++

Borland C++BuilderX Borland C++BuilderX is a commercial programming environment developed by Borland. To help programmers, Borland published a free version, called Personal Edition, that you can download and use for your lessons. 1. On the main menu of C++BuilderX, click File -> New... 2. In the Object Gallery dialog box, click New Console

3. Click OK 4. In the New Console Application - Step 1 of 3, enter the name of the new application in the Name edit box. In this case, you can type Exercise1

5. Click Next

6. In the New Console Application Wizard - Step 2 of 3, accept all defaults and click Next 7. In the New Console Application Wizard - Step 3 of 3, click the check box under Create

8. Click Untitled1 and delete it to replace it with Exercise

9. Click Finish

10. In the Project Content frame, double-click Exercise.cpp to display it in the right frame

11. To execute the application, on the main menu, click Run -> Run Project Borland C++ Builder (Console) Applications Borland C++ Builder is a commercial programming environment developed by Borland. To get, you usually must purchase it. 1. To create a console application in Borland C++ Builder, from the main menu, click File -> New (or File -> new -> Other):

2. From the New Items dialog box. click the Console Wizard button and click OK. 3. From the Console Wizard dialog box, click the C++ radio button and the Console Application check box (the other options are up to you but we will not use them in this tutorial):

4. Click OK. A skeleton program is created for you. For this lesson, I would ask you to delete everything that appears in the Code Editor and type the two lines above, but leave it there. I will not address what all those words mean at this time and we don't even need them and don't care. 5. Change the program as follows:

//--------------------------------------------------------------------------#include <iostream. #include <conio> using namespace std;

#pragma hdrstop //--------------------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

6. To execute the program, on the main menu, click Run -> Run 7. After viewing the result, press Enter to close the DOS window and return to Borland C++ Builder. Linux C++ (Terminal) Applications Most, or all, Linux distributions provide various free C++ compilers. The following instructions are from Red Hat Linux 7.2. 1. To create a C++ application, open the Home Directory (it should have a shortcut on the top left corner of the desktop; otherwise, from the Taskbar, click Start -> KDE menus -> Home Directory) 2. The title bar and the address combo box should display your username. For this exercise, I am logged with the root username. Therefore, my title bar and the address combo box display file:/root With your username selected, right-click in the right frame and click Create New -> Directory...

3. 4. 5. 6.

Type Exercise1 and click OK On the right frame, make sure the Exercise1 directory is created (because I will refer to it). Start a text editor. I use gedit, which is available at Start -> Programs -> Applications -> gedit In the text editor, type the following:

#include <iostream.h> int main() { cout << C++ is fun!!!\n; return 0; }

7.

8. Save your file. If you are using gedit like me, on the main menu, click File -> Save As... 9. Under the Directory header in the left list, double-click the Up One Level button ../ If you see your user name in the left list, fine. Otherwise, double-click ../ again. 10. On the left list, double-click your user name (for me that would be root/) to open you personal directory 11. On the left list, double-click the Exercise1/ directory we created. 12. In the Selection: text box, type the name of the file as Exo.cpp and click OK 13. To execute the program, open the Terminal: Start -> System -> Terminal. In the Terminal window, you should see [UserName@localhost Username]$ For example, mine is [root@localhost root]$ 14. This ensures that you are in your personal directory. To change to the directory that hosts your exercise, type cd Exercise1 Now the new folder should be inside the square brackets. Mine is [Username@localhost Exercise1]$ 15. To compile the program, we will use the free g++ compiler. Therefore, type: g++ Exo.cpp 16. For example, on mine, I type [jezoo@localhost Exercise1]$ g++ Exo.cpp 17. You may receive one warning. For now, don't worry. 18. To execute the program, type ./a.out and press Enter 19. This is because the executable file, named a with the extension .out has been created one folder up from the actual location of the C++ file. For example, on mine, I type [root@localhost Exercise1]$ ./a.out

20. To check the a.out file that was created when compiling, return to the Home Directory window and navigate to the /home/UserName/Exercise1/Exo KDevelop C++ Projects KDevelop is a free programming environment available for the Linux operating system. In some cases, when installing the operating system, you may be prompted whether you want to install KDevelop. Even after the installation, you can add it. If you didn't install it or don't have it on CD or DVD, you can download it free from http://www.kdevelop.org. 1. To create program in KDevelop, start KDevelop by clicking Start -> Development >KDevelop

2. On the main menu, of KDevelop, click Project -> New... 3. From the ApplicationWizard dialog box, in the list or projects, under the Terminal section, click C++ and click Next.

4. In the Project Name edit box, type the name of the project. In this case, type Exercise2 and leave the other edit boxes "as is"; in other words, whatever they contain is fine

5. Uncheck all of the check boxes (make them empty). This is just an option. If you leave them checked, the compiler would generate (a lot of) code for you and I will not have had time to explain those things to you. 6. Click Next 7. Make sure the VCS Support is set to NONE and click Next. 8. Uncheck the headertemplate for .h-files check box (make it empty). Once again, we don't want the compiler to generate code that we haven't learned yet. 9. Click Next. 10. Uncheck the headertemplate for .cpp-files check box. 11. Click Next. 12. Notice the empty window: KDevelop is ready to create the project. 13. Click Create. 14. KDevelop will need a few seconds to create the project. When it has finished, its last line should be READY

15. Therefore, click Exit. 16. To create a (source) file, on the main menu, click File -> New... 17. From the New File dialog box, click C/C++ File (*.cpp,*.c,*.cc,*.C ...) 18. Type Main for the name of the file. Therefore, the Filename edit box should display Main.cpp (you can name the file anything you like, such as Exo or Exercise). 19. Make sure the Add to Project check box is checked and click OK. 20. Leave the grayed section on top of the file (it is just a set of comments that you don't need to delete; they will not affect your program). 21. In the empty section of the file, type:

#include <iostream> using namespace std; int main() { cout << C++ is fun!!!\n;

return 0; }

22. To execute the program, on the main menu, click Build -> Execute 23. After viewing the program, press Enter to close the bash window Microsoft Visual C++ (5, 6) Console Applications Visual C++ is a commercial programming environment developed by Microsoft. You must purchase it if you want to use it (normally, because there is a new version of Visual C++, you may not find Visual C++ 6 anymore from Microsoft). 1. 2. 3. 4. 5. Start Microsoft Visual C++. On the main menu of Microsoft Visual C++ or Microsoft Visual Studio, click File -> New... Click the Projects property sheet. Click Win32 Console Application. In the Location box, type a drive followed by a folder name. For example, type C:\Programs\MSVC 6. In the Project Name, type Exercise1

7. Click OK. 8. In the Win32 Console Application Step 1 of 1, click the An Empty Project radio button

9. Click Finish. 10. You will be presented with another dialog box. Click OK. 11. To create a C++ file, on the main menu, click File -> New... 12. In the New dialog box, make sure the Files property sheet is selected. 13. Click C++ Source File 14. In the File Name, type a name such as Exercise and click OK 15. From what we have learned so far, change the contents of the file as follows:

#include <iostream> using namespace std; int main() { cout << "C++ is fun!!!\n"; return 0; }

16. To execute the program, on the main menu, click Build -> Execute Exercise1.exe 17. When asked to save the project, click Yes 18. After viewing the result, press Enter to close the DOS window and return to MSVC. Microsoft Visual C++ .NET Console Applications Visual C++ .NET is a commercial programming environment developed by Microsoft. It is usually shipped with Microsoft Visual Studio .NET but in some cases, you can purchase it alone. In fact, there is a version made for students and sold at a low price.

1. Start Microsoft Visual Studio .NET. 2. On the main menu of Microsoft Development Environment, click File -> New -> Project... 3. On the New Project dialog box, in the Location box (bottom of the dialog box), type a drive followed by a folder name such as C:\Programs\MSVC .Net 4. In the Project Type, click Visual C++ Projects 5. In the Templates list view, click Win32 Project 6. In the Name box, type Exercise1

7. Click OK. 8. In the Win32 Application Wizard - Exercise1 dialog box, click Application Settings 9. In the Application Type section, click the Console Application radio button 10. In the Additional Options section, click the Empty Project check box

11. Click Finish. 12. To create a new C++ file, on the main menu, click Project -> Add New Item... Or, on the Solution Explorer, right-click Exercise1 -> Add and click Add New Item... 13. In the Categories list, make sure Visual C++ or C++ is selected. 14. In the Templates list view, click C++ File (.cpp) 15. In the Name box, replace the contents with Exercise 16. Click Open 17. From what we know about C++ already, change the contents of the file with:

#include <iostream> using namespace std; int main() { cout << "C++ is fun!!!\n"; return 0; }

18. To execute the program, on the main menu, click Build -> Execute Exercise1.exe 19. When asked to save the project, click Yes 20. After viewing the result, press Enter to close the DOS window and return to MSVC.

Code Fundamentals Using cout There are various ways data get in your program. The first means of entering data in a C++ program is by typing it from the keyboard. Another way would be to instruct the program to receive data from another program then process it. A program can also receive its data or part of it from other hardware devices such as a CD-ROM, a DVD-ROM, a modem, a video camera, etc. To display stuff on the monitor, C++ uses operators. The operator used to display something on the screen is called cout (pronounce see - out) (actually, cout is a class and not an operator, but we haven't learned what a class is). The cout word is followed by the extraction operator <<, then some simple rules to display anything. For example, to display a word or sentence, you include it in double quotes " and ". While you are giving these instructions, you type them in your program. Each C++ instruction is terminated by a semi-colon ";". We have already seen that a program is a set of instructions you give to the computer. These instructions are given inside of functions. This means that an instruction is part of a function. The thing we want to display in our program will be performed by the main() function. In other words, the instruction to display something will be given in main(). Here is an example:
#include <iostream> using namespace std; int main() { cout << "Computer Programming With C++"; return 0; }

Comments The most basic documentation you will (have to) perform is to put comments as much as you can. Comments help you and other people who read your code to figure out what you were doing. Comments are not read by the compiler while executing your program. That means you write them in everyday conversation. There are two usual ways of including comments in your program. To comment the contents of one line, you start it with double forward slashes like this // Here is an example:
// include the first library #include <iostream> using namespace std; int main()

{ // Here is a simple sentence cout << "Hi, this is my program!"; return 0; } // The end of my program

You can include many lines of comments in your program. To do that, comment each line with the double slashes. An alternative is to start the beginning of the commented paragraph with /* and end the commented section with */ Here is another commented version of our program:
// The exo.cpp program // Include the ostream library #include <iostream> using namespace std; int main() { /* Here is a simple sentence that I want to display when the program starts. It doesn't do much. I am planning to do more stuff in the future. */ cout << "Hi, this is my program!"; return 0; } // The end of my program

Variables and Data Types Variables Introduction Your programs will mainly allow the user of your application to interact with the computer. During this interaction, the user will deal with two categories of information: information that is already in the computer and information supplied by the user. Information that is already in the computer will come from various sources; some of that is from the pieces of hardware that compose the users machine, some of that is from the computer (the operating system and other applications that are running on the same computer), and some will have been created by you as part of your application. When interacting with the computer, the user will enter information mainly using the keyboard and/or the mouse. Regardless of what information the user is using, the things used or needed by your program are stored or will be stored in the computer.

To process the information of your program or the requests that your program presents to the user, the computer uses two types of storage spaces. The hard drive is a static storage area that keeps its information all the time, almost regardless of what happens to your computer. Another type of storage used by the computer is referred to as Random Access Memory (RAM). This storage area keeps its information only when the computer is turned on. This means that the RAM looses its Information when the computer is turned off. Strictly stated, when the user opens or launches a program, part of the program goes into the RAM. If or when the application is not used anymore, which means that if the user closes the application, the part of memory that the application was using in the RAM is gone and the memory space that the application was using becomes available (we always hope things go that smooth). As an application developer, you will decide what types of information are necessary for your application and how these things would be used. When creating an application, you will provide these pieces of information to the computer, the computer then puts them together. When your program opens, part of your application gets loaded into the RAM. When the user is using your application, the information that your application requests also goes into the RAM while your application is processing such requests. Because your program will be made of many of these things, the computer needs to know what these things would be, and how much space each one of them would need. Because such a thing can change (vary) throughout your program, it is called a variable. Before using such a variable, you must first let the compiler know. Letting the compiler know about a variable is referred to Declaring the variable. The compiler will need two pieces of information concerning each variable: the amount of space the variable will need, and a name to recognize that variable. Therefore, the formula of declaring a variable is: SpaceOccupied VariableName; C++ Names When using the various necessary variables in your programs, you will need to identify each one of them. A variable is primarily recognized by its name. C++ provides rules for naming items in your program. The name of a variable:

Starts with an underscore _ or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _Score_Side1 Cannot include special characters such as !, %, ], or $ Cannot include an empty space Cannot be any of the reserved words Should not be longer than 32 characters (although allowed)

A name can consist of one word such as country. A name could also be a combination of more than one word, such as firstname or dateofbirth. The C++ compiler has a list of words reserved for its own use and you must not use any of these words to name your own objects or functions. The reserved words are:
C++ Reserved Words

asm break const do except float inline new register sizeof switch try union volatile

auto bad_cast case catch const_cast continue double dynamic_cast explicit extern for friend int long operator private reinterpret_cast return static static_cast template this type_info typedef unsigned using wchar_t while

bad_typeid char default else false goto mutable protected short unsigned throw typeid virtual

bool class delete enum finally if namespace public signed struct true typename void

Most compilers also have their own list of reserved words. Because this depends on the compiler, we cannot review all of them. Avoid starting the name of a variable with two underscores such as __finally or __stdcall. C++ is case-sensitive; this means that CASE, Case, case, and CaSe are four completely different words. To make your programming experience easier and personal, you can add your own rules to those above. Some (most) companies also adopt a naming convention throughout their documentation. Throughout this site:

A name of a variable will start in lowercase. In some situations, a name will start with an underscore, when needed. Examples are country, printer, _number If a name is made of a combination of words, after the first word that starts in lowercase, the first letter of each subsequent word will start in uppercase. Examples are firstName, dateOfBirth

Variables and Their Data Types The amount of memory space necessary to store a variable is also referred to as a data type. A data type provides two valuable pieces of information to the compiler: what amount of space the variable

will use, what kind of information will be allowed in that space. After declaring a variable, the compiler reserves a space in memory for that variable:

A variable, any variable, occupies more that one small cell of space in memory. It will always be your responsibility to decide how much space a variable needs, based on your goal. C You In Besides the cout extractor, C++ is equipped with another operator used to request values from the user. The user usually provides such a value by typing it using the keyboard. The cin (pronounce see in) operator is used for that purpose; it displays a blinking cursor on the monitor to let the user know that a value is expected. Unlike the cout operator, the cin uses two greater than signs >> followed by the name of the expected value. The syntax of the cin operator is:
cin >> valueName;

If you are requesting many values from the user, you can write a statement that would act accordingly by separating values with as many >> operators as necessary. For example, to request a first name, last name, and an age on the same line, you could use:
cin >> firstName >> lastName >> Age;

The Numeric Systems Introduction When you decide to use the computer, if it is off, the first thing you do is to turn it on. As the computer is coming up ( it is booting), you can hear a noise (but many computers now are (very) quiet). It sounds like things are happening inside; things you usually don't care about. In essence, when that noise stops, if everything went fine, the computer loads what is called an operating system. Although the computer is up and you can see some pictures on the screen, no program other than the operating system (and some things we are not concerned about, called utilities) is available: you have to tell the computer, I want to use program A. After clicking a program of your choice, once again you would hear a noise. Depending on the called program, some applications take longer to come up than others. When you call a program, there is an initial setup that the program has to go through to be ready. Such a program uses numbers, characters, meaningful words, pictures, graphics, etc, that are part of the program. As these things are numerous, so is the size of the program, and so is the length of time needed to come up. Your job as a programmer is to create such programs and make them available to the computer, then to people who use the computer.

To write your programs, you will be using alphabetic characters that are a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z. You will also use numeric symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. Additionally, you will use symbols that are not easily readable but are part of the common language; they are ` ~ ! @ # $ % ^ & * ( ) _ + - = : < > ; , . /. Some of these symbols are used in the C++ language while some others are not. When creating your programs, you will be combining letters and/or symbols to create English words or language instructions. Some of the instructions you will give to the computer could consist of counting the number of oranges, converting water to soup, or making sure that a date occurs after January 15. After you have typed an instruction, the compiler would translate it to machine language. Why not send your instructions directly to the computer? This is because the computer does not understand the language you and I speak or write. The computer represents any of your instructions as a group of numbers. Even if you ask the computer to use an orange, it would translate it into a set of numbers. As you give more instructions or create more words, the computer stores them in the computer memory using a certain amount of space for each instruction or each item you use. How much space is necessary? How does the compiler figure out that space? There are three numbering systems that will be involved in your programs, with or without your intervention. The numeric system provides the counting techniques that you use everyday. The hexadecimal system is an intermediary system that allows you to know how the computer deals with numbers. The binary system is the actual system that the computer uses to find out (almost) everything in your program. The Binary System When dealing with assignments, the computer considers a piece of information to be true or to be false. To evaluate such a piece, it uses two symbols: 0 and 1. When a piece of information is true, the computer gives it a value of 1; otherwise, its value is 0. Therefore, the system that the computer recognizes and uses is made of two symbols: 0 and 1. As the information in your computer is greater than a simple piece, the computer combines 0s and 1s to produce all sorts of numbers. Examples of such numbers are 1, 100, 1011, or 1101111011. Therefore, because this technique uses only two symbols, it is called the binary system. When reading a binary number such as 1101, you should not pronounce "One Thousand One Hundred And 1", because such a reading is not accurate. Instead, you should pronounce 1 as One and 0 as zero or o. 1101 should be pronounced One One Zero One, or One One o One. The sequence of the symbols of the binary system depends on the number that needs to be represented. Why learn the binary system? You need to know what the binary system looks like because you will be writing instructions to the computer, and the computer does not understand English. The Decimal System

The numeric system that we have always used uses a set of ten symbols that are 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Each of these symbols is called a digit. Using a combination of these digits, you can display numeric values of any kind, such as 240, 3826 or 234523. This system of representing numeric values is called the decimal system because it is based on 10 digits. When a number starts with 0, a calculator or a computer ignores the 0. Consequently, 0248 is the same as 248; 030426 is the same as 30426. From now on, we will represent a numeric value in the decimal system without starting with 0: this will reduce, if not eliminate, any confusion. Decimal Values: 3849, 279, 917293, 39473 Non- Decimal Values: 0237, 0276382, k2783, R3273 The decimal system is said to use a base 10. This allows you to recognize and be able to read any number. The system works in increments of 0, 10, 100, 1000, 10000, and up. In the decimal system, 0 is 0*100 (= 0*1, which is 0); 1 is 1*100 (=1*1, which is 1); 2 is 2*100 (=2*1, which is 2), and 9 is 9*100 (= 9*1, which is 9). Between 10 and 99, a number is represented by left-digit * 101 + right-digit * 100. For example, 32 = 3*101 + 2*100 = 3*10 + 2*1 = 30 + 2 = 32. In the same way, 85 = 8*101 + 5*100 = 8*10 + 5*1 = 80 + 5 = 85. Using the same logic, you can get any number in the decimal system. Examples are: 2751 = 2*103 + 7*102 + 5*101 + 1*100 = 2*1000 + 7*100 + 5*10 + 1 = 2000 + 700 + 50 + 1 = 2751 67048 = 6*104 + 7*103 + 0*102 + 4*101 + 8*100 = 6*10000 + 7*1000+0*100+4*10+8*1 = 67048 Another way you can represent this is by using the following table: etc Add 0 to the preceding value 1000000 100000 10000 1000 100 10 0

When these numbers get large, they become difficult to read; an example is 279174394327. To make this easier to read, you can separate each thousand fraction with a comma. Our number would become 279,174,394,327. You can do this only on paper, never in a program: the compiler would not understand the comma(s). Why use the decimal system? Because, to represent numbers, that is the only system that you and I are familiar with. The Hexadecimal System While the decimal system uses 10 digits (they are all numeric), the hexadecimal system uses sixteen (16) symbols to represent a number. Since the Latin language consists of only 10 digits, we cannot make up new ones. To compensate for this, the hexadecimal system uses alphabetic characters. After counting from 0 to 9, the system uses letters until it gets 16 different values. The letters used are a, b, c, d, e, and f, or their uppercase equivalents A, B, C, D, E, and F. The hexadecimal system counts as follows: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, and f; or 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Once again, to produce a number, you use a combination of these sixteen symbols. Examples of

hexadecimal numbers are 293, 0, df, a37, c23b34, or ffed54. At first glance, the decimal representation of 8024 and the hexadecimal representation of 8024 are the same. Also, when you see fed, is it a name of a federal agency or a hexadecimal number? Does CAB represent a taxi, a social organization, or a hexadecimal number? From now on, to express the difference between a decimal number and a hexadecimal one, each hexadecimal number will start with 0x or 0X. The number will be followed by a valid hexadecimal combination. The letter can be in uppercase or lowercase. Legal Hexadecimals: 0x273, 0xfeaa, 0Xfe3, 0x35FD, 0x32F4e Non-Hex Numbers: 0686, ffekj, 87fe6y, 312 Why learn or use the hexadecimal system? Because the computer does not understand the decimal system, which is our everyday base of counting items, and because we do not understand or are not familiar with the binary system, the hexadecimal system provides an intermediary system. Also, the hexadecimal system represents shorter words to represent the same numbers in the decimal system. Signed and unsigned The numbers we have used so far were counting from 0, then 1, then 2, and up to any number desired, in incrementing values. Such a number that increments from 0, 1, 2, and up is qualified as positive. By convention, you do not need to let the computer or someone else know that such a number is positive: by just displaying or saying it, the number is considered positive. This is the basis of our counting items. In real life, there are numbers counted in decrement values. Such numbers start at 1 and move down to -2, -3, -4 etc. These numbers are qualified as negative. When you write a number normally, such as 42, 502, or 1250, the number is positive. If you want to express the number as negative, you use the on the left side of the number. The symbol is called a sign. Therefore, if the number does not have the symbol, C++ (or the compiler) considers such a number as unsigned. In C++, if you declare a variable that would represent a numeric value and you do not initialize (assign a value to) such a variable, the compiler will consider that the variable can hold either a signed or an unsigned value. If you want to let the compiler know that the variable should hold only a positive value, you will declare such a variable as unsigned. Representing Numbers A Bit The computer (or an Intel computer, or a computer that runs on an Intel microprocessor) uses the binary system to represent its information. A piece of information in the computer is called a datum; and the plural is data. Sometimes, the word data is used for both singular and plural. The computer represents data using only a 0 or 1 values. To make an illustration, let's consider that a

computer uses a small box to represent such a value. This small box can have only one of two states. When the box is empty, we will give it a value of 0. When the box is full, we give it a value of 1. The box can have only one of these two values.

Since this box can have only one of two states, consider that you can use it to represent anything that could assume one out of two states. Examples include: True-False; Parent-Child; On-Off; DiscountNoDiscount; Male-Female; Yes-No, etc. This technique of representing values is called The Binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system. Although this is valid for the computer, the Intel microprocessors cannot validate a variable at this level; but eventually, you will be able to manipulate data at the bit level. Although the C++ compiler recognizes a bit, you cannot store a variable in a bit. However, eventually, you will be able to manipulate the information stored in a bit. The single bit is used only to represent a tinny piece of information. To get effective numbers, the computer combines the bits. The first combination of bits consists of grouping four consecutive bits.

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

The first bit, on the right side of the nibble, is called the Low Order bit or LO bit. This is also called the least significant bit. The last bit, on the left side of the nibble, is called the High Order bit or HI bit; it is also called the most significant bit. The bit on the right side is counted as bit 0. The bit on the left side is counted as bit 3. The other bits are called by their positions: bit 1 and bit 2. Once again, each bit can have one of two states. Continuing with our illustration, when a box is empty, it receives a value of 0. Otherwise, it has a value of 1. On a group of four consecutive bits, we can

have the following combinations:

This produces the following binary combinations: 0000, 0001, 0010, 0011, 0100, 0101, 0110, 0111, 1000, 1001, 1010, 1011, 1100, 1101, 1110, 1111 = 16 combinations. When using the decimal system, these combinations can be represented as 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, and 15. As you can see, a nibble is represented by a group of 4 bits. This is also a system that the computer uses to count bits internally. Sometimes, in your program or in the help files, you will encounter a number that is less than four bits, such as 10 or 01 or 101. How do you reconcile such a number to a nibble? The technique used to complete and fill out the nibble consists of displaying 0 for each nonrepresented bit. The binary number 10 will be the same as 0010. The number 01 is the same as 0001. The number 101 is the same as 0101. This technique is valuable and allows you to always identify a binary number as a divider of 4. When all bits of a nibble are 0, you have the lowest value you can get, which is 0000. Any of the other combinations has at least one 0 bit, except for the last one. When all bits are 1, this provides the highest value possible for a nibble. The lowest value, also considered the minimum value, can be represented in the decimal system as 0. The highest value, also considered the maximum, can be expressed in decimal value as 24 (2 represents the fact that there are two possible states: 0 and 1; 4 represents the fact that there are four possible combinations), which is 16. This produces 16 because 24 = 16. As you can see, the binary system is very difficult to read when a value combines various bit representations. To make your life a little easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:
Decimal Hexadecimal Binary

0 1 2

0 1 2

0000 0001 0010

3 4 5 6 7 8 9 10 11 12 13 14 15

3 4 5 6 7 8 9 A B C D E F

0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

Table of Numeric Conversions

When looking at a binary value represented by 4 bits, you can get its decimal or hexadecimal values by referring to the table above. For this reason, you may have to memorize it. A nibble, which is a group of four consecutive bits, has a minimum and maximum values on each system as follows:
Decimal Minimum Maximum Hexadecimal Binary

0 15

0x0 0xf

0000 1111

Although the C++ compiler recognizes a group of four consecutive bits, you cannot store any variable in a nibble. You can, however, manipulate the bits of a nibble. A Byte Representing a Byte

A byte is a group or eight consecutive bits. The bits are counted from right to left starting at 0. The most right bit is bit 0; it is called the least significant bit. It is also referred to as the Low Order bit, the LO bit, or LOBIT. The most left bit is bit 7; it is called the most significant bit. It is also referred to as the High Order bit, the HI bit, or HIBIT. The other bits are referred to following their positions. A byte is considered as being made of two nibbles. The right nibble, made of the right 4 bits, is called

the Low Order nibble or LO nibble. The left nibble, made of the left 4 bits, is called the High Order nibble or HI nibble.

Using the binary system, you can represent the byte using a combination of 0s and 1s. When all bits have a value of 0, the byte is represented as 00000000. On the other hand, when all bits have a value of 1, the byte is represented as 11111111. When the number grows very large, it becomes difficult to read. Therefore, we will represent bits in groups of four. Instead of writing 00000000, we will write 0000 0000. This makes the number easier to read. If you have the patience to create combinations of bits using the boxes as we did for the nibble, you would find out that there are 256 possible combinations. Another way to find it out is by using the base 2 technique: 27 + 26 + 25 + 24 + 23 + 22 + 21 + 20 = 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 Therefore, the maximum decimal value you can store in a byte is 255. Remember that the byte with all bits having a value of 0 has its value set to 0. Since this byte also holds a valid value, the number of combinations = 255 + 1 = 256. When a byte is completely represented with 0s, it provides the minimum value it can hold; this is 0000 0000, which is also 0. When all bits have a value of 1, which is 1111 1111, a byte holds its maximum value that we calculated as 255 in the decimal system. As done with the nibble, we get the following table:
Decimal Minimum Maximum Hexadecimal Binary

0 255

0x0 0xff

0000 1111 1111

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

decimal, a hexadecimal, and a binary equivalents. Each one of the characters you see on your keyboard is represented as a numeric value, but whether it appears as a number, a letter, or a symbol, each one of these is considered a character. To display any character on your screen, you can use the cout << operator and include the character between singlequotes, as follows:
#include <iostream> using namespace std; int main() { cout << 'a'; return 0; }

Character Variables A byte is used to hold a single character. A character is an individual symbol that displays on your screen. It could be:

A lowercase letter: a, b, c, d, e, f, g, h, I, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z An uppercase letter: A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, And Z A digit: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9; A special characters : ` ~ # $ ! @ % ^ & * ( { [ ) } ] | \ : ; + - < _ ? > , / =.

To declare a variable as a character, use the C++ keyword char followed by a valid C++ name. Here is an example:
char Gender;

With a byte variable declared like that, you can give the variable a starting value. Giving a value to a variable is referred to as initializing it. Initializing a variable is done with the = operator. The syntax used is:
VariableName = Value;

Since a char variable represents one symbol, to initialize it, enclose the initial value in single quotes. Here is an example:
char Answer = y;

You can also initialize a variable by including its value between parentheses as follows;
char Answer(y);

To display the value of an initialized variable, use the cout << extractor and type the name of the

variable. Here is an example:


#include <iostream> using namespace std; int main() { char category = 'H'; cout << "Category: " << category; cout << endl; return 0; }

If the character is of a signed category, you can declare it as a signed character. This type of variable would be an 8-bit integer whose value can range from 128 to +127. Here is an example:
#include <iostream> using namespace std; int main() { signed char category = 'D'; cout << "Category: " << category << endl; return 0; }

You can also declare a positive character as unsigned char. Here is an example:
#include <iostream> using namespace std; int main() { char letter = 'L'; char category = 'n'; unsigned char sound('x); cout << "Pick " << Pick; cout << category; cout << "Sound " << sound; return 0; }

To request a byte variable, type the name of the variable on the right side of the cin >> extractor followed by a semi-colon as follows:
#include <iostream> using namespace std;

int main() { char Satisfaction, answer; signed char ageCategory, size; cout << "From A to Z, enter a character as your level of satisfaction: "; cin >> satisfaction; cout << "Age category(t=teen/a=Adult/s=Senior): "; cin >> ageCategory; cout << "Are you drunk(y=Yes/n=No)? "; cin >> answer; cout << "Enter your size(s=Small/m=Medium/l=Large): "; cin >> size; cout cout cout cout } << << << << "\nSatisfaction: " << Satisfaction; "\nAge category: " << AgeCategory; "\nYour answer: " << Answer; "\nYour size: " << Size;

return 0;

To keep the integer value of a char positive, you can declare it as an unsigned char. Its value would then range from 0 to 255. Escape Sequences When you use alphabetic characters in your program, the compiler considers them as numbers but converts each to its corresponding character following the ASCII list. Counting decimal values starting at 0, the first 32 characters actually do not display anything on the screen: they are called non-printing characters. They are obtained from pressing Ctrl and an alphabetic letter or a symbol. The exception is that the 8th to 12th characters are used to control some of the characters and they are called escape sequences. To use one of these escape sequences, you include it preceded by a backslash; you can include both in single-quotes. For example, the \n is used to ask the compiler to stop the line and start the remaining program to the next line; this is referred to Carriage Return Line Feed. The \n escape sequence could be used as follows:
#include <iostream> using namespace std; int main() { cout << "Sydney\nAustralia\n"; return 0; }

Besides the \n escape sequence, you can also use the endl keyword to move the cursor to the next line. Here is the list of escape sequences: Escape Name Sequence \a Bell (alert) \b Backspace Horizontal \t Tab \n \v \f \r \" \' \? \\ \0 New line Vertical Tab Form feed Carriage return Double Quote Apostrophe Question mark Backslash Null ASCII Description value 007 Makes a sound from the computer 008 Takes the cursor back 009 Takes the cursor to the next tab stop Takes the cursor to the beginning of the next line 011 Performs a vertical tab 012 010 013 Causes a carriage return 034 Displays a quotation mark (") 039 Displays an apostrophe (') 063 Displays a question mark 092 Displays a backslash (\) 000 Displays a null character

<a href="http://c.casalemedia.com/c?s=56757&f=2&id=3538610468.6314845" target="_blank" src="http://as.casalemedia.com/s?s=56757&u=http%3A//www.functionx.com/cpp/Lesson02.htm&f=2&id=3538 width="728" height="90" border="0"></a>

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

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

The most fundamental representation of a word in binary format is 0000000000000000. To make it easier to read, you can group bits in 4, like this: 0000 0000 0000 0000. Therefore, the minimum binary value represented by a word is 0000 0000 0000 0000. The maximum binary value represented by a word is 1111 1111 1111 1111. The minimum decimal value of a word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula, filling out each bit with 1: 1*215+1*214+1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20 = 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 65535 The minimum hexadecimal value you can store in a word is 0x0000000000000000. This is also represented as 0x00000000, or 0x0000, or 0x0. All these numbers produce the same value, which is 0x0. To find out the maximum hexadecimal number you can store in a word, replace every group of 4 bits with an f or F: 1111 1111 1111 1111 ffff = 0xffff = 0xFFFF = 0Xffff = 0XFFFF

Short Integers A word, which is a group of 16 contiguous bits or 2 bytes, is used to represent a natural number. As we have studied, the maximum numeric value that can fit in a word is 65535. Since the Byte is used only to represent a character, whenever you plan to use a number in your program, the minimum representation you should/must use is a word. An algebraic natural number is also called an integer. The smallest integer you can store in a word is declared with the short keyword followed by a name. Because a short integer is signed by default, it can store a value that ranges from 32768 to 32767. Here is an example program that uses two short integers:
#include <iostream> using namespace std; int main() { short number1, number2; cout << "Enter a number between -32768 and 32767: "; cin >> number1; cout << "Enter another number: "; cin >> number2; cout << "\nThe numbers you entered were\n"; cout << "\tNumber 1: " << number1 << "\n"; cout << "\tNumber 2: " << number2 << "\n"; return 0; }

By default, a short integer is signed. You can also explicitly declare such a variable as a signed short. Here is an example:
signed short XCoord;

If the integer must be positive, you should declared as an unsigned short. The unsigned short is used to identify a 16-bit positive integer whose value would range from 0 to 65535. Practical Learning: Using Short Integer Variables 1. Start your programming environment and create a new project named GCS1. Depending on your environment, if the file was not created already, then create a source file and save it as, or name it exercise.cpp 2. Set the file's content as follows:
#include <iostream> using namespace std; int main() {

unsigned unsigned unsigned unsigned

short short short short

shirts; pants; dresses; ties;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout << << << << "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order" << "\nItem Type Qty" << "\nShirts: " << shirts << "\nPants: " << pants << "\nDresses: " << dresses << "\nTies: " << ties << "\n\n";

return 0; }

3. Execute the application and perform the exercise. Here is an example:

-=- Georgetown Cleaning Services -=Enter Enter Enter Enter number number number number of of of of shirts: 6 pants: 2 dresses: 3 ties: 4

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Item Type Qty Shirts: 6 Pants: 2 Dresses: 3 Ties: 4

4. Return to your programming environment

A Double-Word Representing a Double-Word A double-word is a group of two consecutive Words. This means that a double-word combines 4 bytes, or 8 nibbles, or 32 bits. The bits, counted from right to left, start at 0 and end at 31.

The most right bit, bit 0, is called the Low Order bit or LO bit or LOBIT. The most left bit, bit 31, is called the High Order bit or HI bit or HIBIT. The other bits are called using their positions. The group of the first 8 bits (from bit 0 to bit 7), which is the right byte, is called the Low Order Byte, or LO Byte. It is sometimes referred to as LOBYTE. The group of the last 8 bits (from bit 24 to bit 31), which is the left byte, is called the High Order Byte, or HI Byte or HIBYTE. The other bytes are called by their positions. The group of the right 16 bits, or the right Word, is called the Low Order Word, or LO Word, or LOWORD. The group of the left 16 bits, or the left Word, is called the High Order Word, or HI Word, or HIWORD.

The minimum binary number you can represent with a double-word is 0 The minimum decimal value of a double-word is 0. To find out the maximum decimal value of a word, you can use the base 2 formula giving a 1 value to each bit: 2n-1 230 229 228 227 226 225 224 etc 1,073,741,824 536,870,912 268,435,456 134,217,728 67,108,864 33,554,432 16,777,216

223 222 221 220 8,388,608 4,194,304 2,097,152 1,048,576 215 32,768 27 128 214 16,384 26 64 213 8,192 25 32 212 4,096 24 16

219 524,288 211 2,048 23 8

218 262,144 210 1,024 22 4

217 131,072 29 512 21 2

216 65,536 28 256 20 1

1*231+1*230+1*229 + 1*228 + 1*227 + 1*226 + 1*225 + 1*224 + 1*223 + 1*222 + 1*221 + 1*220 + 1*219 + 1*218 + 1*217 + 1*216 + 1*215 + 1*214 + 1*213 + 1*212 + 1*211 + 1*210 + 1*29 + 1*28 + 1*27 + 1*26 + 1*25 + 1*24 + 1*23 + 1*22 + 1*21 + 1*20 = 2,147,483,648 + 1,073,741,824 + 536,870,912 + 268,435,456 + 134,217,728 + 67,108,864 + 33,554,432 + 16,777,216 + 8,388,608 + 4,194,304 + 2,097,152 + 1,048,576 + 524,288 + 262,144 + 131,072 + 65,536 + 32,768 + 16,384 + 8,192 + 4,096 + 2,048 + 1,024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 4,286,578,708 The minimum hexadecimal value you can store in a word is 0x0. To find out the maximum hexadecimal number you can represent with a word, replace every group of 4-bits with an f or F: 1111 1111 1111 1111 1111 1111 1111 1111 f f f f f f f f = 0xffffffff = 0Xffffffff = 0XFFFFFFFF = 0xFFFFFFFF Using Integers A double-word is large enough to contain double the amount of data that can be stored in a word. This is equivalent to 32 bits or 4 bytes or 4294967295. Therefore, a double-word is used for large numbers that would not fit in a word. An integer is a natural number typically used to count items. For an integer variable whose value requires more memory space than a word can hold, declare it using the int keyword. The integer data type is used for a variable whose value can range from 2,147,483,648 to 2,147,484,647. Here is an example:
#include <iostream> using namespace std; int main() { int coordX, coordY, coordZ; cout << "Enter the coordinates of point A\n";

cout << "Horizontal X = "; cin >> coordX; cout << "Vertical Y = "; cin >> coordY; cout << "Depth Z = "; cin >> coordZ; cout cout cout cout } << << << << "\nOn a cartesian system, point A is located at"; "\n\tX = " << coordX; "\n\tY = " << coordY; "\n\tZ = " << coordZ;

return 0;

When executed, the program would produce: Enter the coordinates of point AHorizontal X = -12Vertical Y = 8Depth Z = 6On a cartesian system, point A is located at X = -12 Y = 8 Z = 6Press any key to continue... The signed is used to designate an integer variable whose value could be negative or positive. You can declare such a variable using one of the following:
signed distanceRange; signed int velocity;

When declared with int, an integer is considered as signed. You can also explicitly declared such an integer as signed int. Here is an example:
signed int pagePosition;

If the variable must be positive, you can declared it an unsigned int. The unsigned int is used to identify a 32-bit positive integer variable whose value would range from 0 to 2,147,484,647. Here is an example:
unsigned int pageCount;

An unsigned integer can also be declared simply with the unsigned keyword. Here is an example:
#include <iostream> using namespace std; int main() { unsigned dayOfBirth, monthOfBirth, yearOfBirth; cout << "The following pieces of information " << "are required for each student\n"; cout << "Day of Birth: "; cin >> dayOfBirth; cout << "Month of Birth: "; cin >> monthOfBirth; cout << "Year of Birth: "; cin >> yearOfBirth;

cout << "\nStudent's Date of Birth: " << dayOfBirth << "/" << monthOfBirth << "/" << yearOfBirth; return 0; }

Practical Learning: Using Integer Variables 1. To use integer variables, change the source file as follows:

#include <iostream> using namespace std; int main() { unsigned unsigned unsigned unsigned

short short short short

shirts; pants; dresses; ties;

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout cout "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Qty"; cout << "\n------------------------------------" << "\nShirts: " << shirts << "\nPants: " << pants << "\nDresses: " << dresses << "\nTies: " << ties << << << << <<

<< "\n\n"; return 0; }

2. Execute the application and test the exercise. Here is an example:

-=- Georgetown Cleaning Services -=Enter Order Order Order Enter Enter Enter Enter the date this order was placed Day: 18 Month: 06 Year: 2000 number of shirts: 2 number of pants: 0 number of dresses: 3 number of ties: 0

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Order Date: 6/18/2000 -----------------------------------Item Type Qty -----------------------------------Shirts: 2 Pants: 0 Dresses: 3 Ties: 0

3. Return to your programming environment

Long Integers An integer variable whose value should be positive can also be declared with the long keyword. The long keyword designates a positive 32-bit integer whose value ranges from 0 to 4,294,967,295. Here is an example:
long countryArea;

To enforce the long integer being positive, you can declare its variable as an unsigned long. The following program illustrates that:
#include <iostream> using namespace std; int main() { long USPopulation; unsigned long USArea;

cout << "What is the area of the US? "; cin >> USArea; cout << "What is the population of the US? "; cin >> USPopulation; cout << "\nCharacteristics of the US"; cout << "\n\tArea = " << USArea << "\n\tPopulation = " << USPopulation; return 0; }

Floating-Point Numbers Floating-Point Numbers With Single-Precision The integers we have used so far have the main limitation of not allowing decimal values. C++ provides floating identifier values that would solve this problem. The most fundamental floating variable is declared with the float keyword. The float is a 4 Byte real number that ranges from 3.4 x 10-38 to 3.4 x 1038. To declare a floating variable, use the float keyword followed by the name of the variable. Here are examples:
float side; float length;

To initialize a floating variable, after declaring it, assign it a value using the Assignment operator =, like this:
float priceSoda; priceSoda = 0.85;

You can also initialize the variable using the parentheses, like this:
float priceOrangeJuice(2.25);

To request a floating-point variable from the user, use the cin >> operator, like this
cin >> variable;

Like an initialized variable, you can perform any desired operation on such a variable. Here is an example program that requests the side of a square and then calculates the perimeter and the area:
#include <iostream> using namespace std; int main() { float side, perimeter, area;

cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout cout cout cout } << << << << "Characteristics of the square:"; "\nSide: " << side; "\nPerimeter: " << perimeter; "\nArea: " << area;

return 0;

Floating-Point Numbers With Double-Precision When a variable is larger than the float can handle and requires more precision, you should use the double identifier. The double-precision identifier is an 8 Byte decimal or fractional number ranging from 1.7 x 10-308 to 1.7 x 10308. Here is an example:
#include <iostream> using namespace std; int main() { float side, perimeter, area; cout << "Enter the side of the square: "; cin >> side; perimeter = side * 4; area = side * side; cout cout cout cout } << << << << "Characteristics of the square:"; "\nSide: " << side; "\nPerimeter: " << perimeter; "\nArea: " << area;

return 0;

For an even larger variable, use the 10 Byte real data type identified as a long double data type that ranges from 3.4 x 10-4932 to 1.1 x 104932. Here is an example that uses the long double data type:
#include <iostream> using namespace std; int main() { long double radius = 15.625, Radius = 18.125; long double area, Area, TotalArea; Area = Radius * Radius * 3.14159; area = radius * radius * 3.14159;

TotalArea = Area - area; cout cout cout cout } << << << << "Properties of the plate"; "\nExternal Radius: " << Radius; "\nInternal Radius: " << radius; "\nArea: " << TotalArea;

return 0;

Practical Learning: Using Floating-Point Numbers 1. To use decimal variables, change the source file as follows:

#include <iostream> using namespace std; int main() { unsigned unsigned unsigned unsigned double double double double

short short short short

shirts; pants; dresses; ties; = = = = 1.25; 2.75; 3.25; 1.65;

priceShirts pricePants priceDresses priceTies

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout cout << << << << << "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nOrder Date: " << orderMonth

<< '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty"; cout << "\n------------------------------------" << "\nShirts: " << priceShirts << " " << shirts << "\nPants: " << pricePants << " " << pants << "\nDresses: " << priceDresses << " " << dresses << "\nTies: " << priceTies << " " << ties << "\n\n"; return 0; }

2. Execute the application and perform an order. Here is an example:

-=- Georgetown Cleaning Services -=Enter the date this order was placed Order Day: 14 Order Month: 10 Order Year: 2002 Enter number of shirts: 5 Enter number of pants: 2 Enter number of dresses: 3 Enter number of ties: 2 ==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Order Date: 10/14/2002 -----------------------------------Item Type Unit Price Qty -----------------------------------Shirts: 1.25 5 Pants: 2.75 2 Dresses: 3.25 3 Ties: 1.65 2

3. Return to your programming environment

Introduction to Strings A Group of Characters A group of characters is called an array. This is a study we will cover when learning about arrays. For now, if you want to use a group of characters of any kind, declare a variable starting with a char data type, followed by a valid name for the variable, followed by an opening square bracket [, followed by a number of characters, followed by a closing square bracket ], and ended with a semi-colon. The syntax to declare a group of characters is:

char VariableName[NumberOfCharacters];

The char keyword is required to let the compiler know that you want to create a variable of type char. The created variable must have a valid name. The number of characters, called the dimension of the array, should be an estimate; for example, if you want to request employees first names, type a number that you think would represent the largest name possible. The maximum number should be 80, but the average and a good regular number should be between 12 or 20. To represent an address or a similar long group of characters, use a dimension between 32 and 50. Examples of declaring arrays of characters are:
char FirstName[12]; char LastName[12];

To initialize an array of characters, do not specify the dimension and leave the square brackets empty. You can use the assignment operator and include the initialized variable in double-quotes. Another technique, is to include the value between parentheses. Here is a program with two techniques of initializing arrays of characters:
#include <iostream> using namespace std; int main() { char University[] = "University of the District of Columbia"; char Faculty[]("Computer sciences"); cout cout cout cout } << << << << "Welcome to the Student Orientation Program.\n"; "For your studies, we have selected:\n"; "Institution: " << University << "\n"; "Faculty: " << Faculty << "\n";

return 0;

To request an array from the user, simply type the name of the array variable on the right side of the cin >> operator. Here is an example:
#include <iostream> using namespace std; int main() { char FirstName[12]; char LastName[12]; cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName; cout << "\nFull Name: " << FirstName << " " << LastName;

cout << endl; return 0; }

To request a group of words using an array, use one of the following functions:
cin.getline( VariableName, Dimension); cin.getline(VariableName, Dimension, Delimeter);

To use the array variables, change the content of the file as follows:
#include <iostream> using namespace std; int main() { char FirstName [20], LastName [20]; char Address [40]; char JobPerformed [80]; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> ws; cin.getline(FirstName, 20); cout << "Last Name: "; cin >> ws; cin.getline(LastName, 20); cout << "Address: "; cin >> ws; cin.getline(Address, 40); cout << "Describe the job performed on the customer's car in 100 words or less:\n"; cin >> ws; cin.getline(JobPerformed, 80); cout cout cout cout cout } << << << << << "\nCPAP Invoice # 1202"; "\nCustomer Name: " << FirstName << " " << LastName; "\nAddress: " << Address; "\nJob Performed: " << JobPerformed; "\n\n";

return 0;

Practical Learning: Using Strings The following exercise was tested only in Microsoft Windows. The cin >> ws operation may not work on other operating systems but you would have to test it for yourself. Thanks. 1. To use string variables, change the source file as follows:

#include <iostream> using namespace std; int main() { char customerName[60], customerPhone[20]; unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; double double double double priceShirts pricePants priceDresses priceTies = = = = 1.25; 2.75; 3.25; 1.65;

int orderDay; int orderMonth; int orderYear; cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: "; cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: "; cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; cout cout cout cout cout cout cout "\n===================================="; "\n-=- Georgetown Cleaning Services -=-"; "\n===================================="; "\nCustomer Order"; "\nCustomer Name: " << customerName; "\nCustomer Phone: " << customerPhone; "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty"; << << << << << << <<

cout << "\n------------------------------------" << "\nShirts: " << priceShirts << " " << "\nPants: " << pricePants << " " << "\nDresses: " << priceDresses << " " << "\nTies: " << priceTies << " << "\n\n"; return 0; }

<< shirts << pants << dresses " << ties

2. Execute the application and perform an order. Here is an example:

Enter Order Order Order Enter Enter Enter Enter

the date this order was placed Day: 02 Month: 11 Year: 2001 number of shirts: 6 number of pants: 4 number of dresses: 2 number of ties: 0

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Jeannot Arnolds Customer Phone: (301) 938-2240 Order Date: 11/2/2001 -----------------------------------Item Type Unit Price Qty -----------------------------------Shirts: 1.25 6 Pants: 2.75 4 Dresses: 3.25 2 Ties: 1.65 0

3. Return to your programming environment Strings A string is a character, a group of characters, or an empty space that you want the compiler to treat as is. Besides using an array of characters, a special library called the Standard Template Library provides an alternative. You can declare a string using the string keyword. To use a string in your program, first include the string library using the using namespace keywords followed by std;. In your program, declare a variable starting with the word string followed by a valid name for the variable. Here are examples: string Continent;

string Company; When requesting its value from the user, by default, the string identifier is used to get only a oneword variable. Here is an example program that requests a first and last names:
#include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Enter first name: "; cin >> FirstName; cout << "Enter last name: "; cin >> LastName; cout << "\n\nFull Name: " << FirstName << " " << LastName << "\n\n"; return 0; }

You can initialize a string variable of any length. One technique is to use the assignment operator and include the string in double-quotes. Here is an example:
string UN = "United Nations"; cout << "The " << UN << " is an organization headed by a Secretary General";

Another technique involves using parentheses following the name of the string variable, and including the string in double-quotes. Here is an example:
string BookTitle("Drugs, Sociology, and Human Behavior."); cout << "For our class next week, please read \"" << BookTitle;cout << "\"";

If you want to request the value of the variable from the user, you should use the getline function. To use the getline function, follow this formula:
getline(cin, StringName);

Inside of the parentheses, the word cin informs the compiler that the request will come from an external source, mainly the user typing from the keyboard. The StringName is the name you declared the variable with. The getline() function expects that the user will press Enter to end the sentence; the end line character is \n. Here is an example program that requests strings of any length from the user:
#include <iostream> #include <string>

using namespace std; int main() { string MusicAlbum; string TrackTitle; cout << "Welcome to Radio Request where the listeners select their songs:\n"; cout << "Type the album name: "; getline(cin, MusicAlbum); cout << "Type the song title: "; getline(cin, TrackTitle); cout << "\nNow for your pleasure, we will play: " << TrackTitle << "\nfrom the " << MusicAlbum << " wonderful album.\n\n"; return 0; }

If you want the user to end the sentence with another character such as * or !, use the following function
getline(cin, StringName, Delimiter);

The following example uses the = symbol as the end character of the sentence:
string Address; cout << "Enter your address. To end, type = "; getline(cin, Address, '='); cout << "\nSo, you live at: " << Address;

Here is an example:
#include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "\n\nCPAP Invoice # 1202"; cout << "\nCustomer Name: " << FirstName << " " << LastName << "\n\n"; return 0;

When requesting a string made of various words, such as an address, you can use the getlin() function as follows:
#include <iostream> #include <string> using namespace std; int main() { string FirstName, LastName; string Address; string JobPerformed; cout << "Welcome to College Park Auto-Parts\n"; cout << "Enter the following information about the customer's.\n"; cout << "First Name: "; cin >> FirstName; cout << "Last Name: "; cin >> LastName; cout << "Address: "; getline(cin, Address); cout << "Describe the job performed on the customer's car:\n"; getline(cin, JobPerformed); cout cout cout cout } << << << << "\n\nCPAP Invoice # 1202"; "\nCustomer Name: " << FirstName << " " << LastName; "\nAddress: " << Address; "\nJob Performed: " << JobPerformed << "\n\n";

return 0;

C++ Support for Code Writing Value Casting Introduction We have been introduced to declaring variables using specific data types. After declaring a value and initializing it, you may want the value to change type without redefining it. This is required in some cases where you already have a value, probably produced by one variable, while another variable declared with a different data type. This means that you would need to convert a value from one type into another type. For example, you may have declared a variable using a double data type but you need the value of that variable to be used as an int. Transferring a value from one type to another is referred to as casting.

There are two broad types of casting available in C++: C's old school of casting and the C++ standards. C How To Cast a Value C, the parent of C++ supports value casting by specifying the type of value you want an existing one to have. To do this, you use the following formula:
(DataType)Expression

Based on this formula, in the parentheses, enter the type of data you want the existing or resulting value to have. The DataType factor can be any of the data types we saw above. The Expression factor can be a constant value. Here is an example:
#include <iostream> using namespace std; int main() { cout << "Number: " << (int)3.14159 << "\n"; return 0; }

Notice that the value to convert is a floating-point number. If the conversion is successful, the new value would be conform to the type in parentheses. For example, the above code would produce:
Number: 3

Here is another version of the above program:


#include <iostream> using namespace std; int main() { int number; number = (int)3.14159; cout << "Number: " << number << "\n"; return 0; }

The Expression factor can also be the result of a calculation. In this case, you should include the whole expression is its own parentheses. The Expression factor of our formula can also be the name of a variable that holds a value. Here is an example:

#include <iostream> using namespace std; int main() { double price = 258.85; int number; cout << "Price? $" << price << "\n"; number = (int)price; cout << "Number: " << number << "\n"; return 0; }

This would produce:


Price? $258.85 Number: 258

C++ Casting C++ provides its own support of value casting using variable keywords so you can specify the type of conversion you want. One of the keywords used is static_cast and the formula is:
static_cast<DataType>(Expression)

In this formula, the static_cast keyword, the <, the >, and the parentheses are required. The DataType factor should be an existing data type such as those we have reviewed in this lesson. The Expression factor can be a constant value. Here is an example that converts a floating-point number to an integer:
#include <iostream> using namespace std;

int main() { cout << "Number: " << static_cast<int>(3.14159) << "\n";

return 0; }

You can also assign the resulting value to a variable before using it:
#include <iostream> using namespace std;

int main() { int number = static_cast<int>(3.14159);

cout << "Number: " << number << "\n";

return 0; }

The value to convert can also be the result of a calculation. The value can also be originating from an existing variable whose value you want to convert to a new type. Here is an example:
#include <iostream> using namespace std;

int main() { double PI = 3.14159; int number;

number = static_cast<int>(PI);

cout << "PI = " << PI << endl; cout << "Number = " << number << "\n";

return 0;

This would produce:


PI = 3.14159 Number = 3

Variable Scope Introduction So far, to declare a variable, we proceeded inside of the main() function. Such a variable could be used only inside of the square brackets of main(). In some cases, you may want to declare a variable that can be accessed from one section of the code. The section of code in which a variable can be accessed is referred to as its scope. Local Variables If you declare a variable inside of a function such as main(), that function can be accessed only from that function. Consider the following example:
#include <iostream> using namespace std;

int main() { double number = 3.14159; cout << "Number = " << number << "\n";

return 0; }

Such a variable is referred to as local because it is declared in a function. In reality, a local scope is defined by a beginning opening curly bracket "{" and a closing curly bracket "}". Everything between these brackets belongs to a local scope. Once you have declared such a variable, you cannot declare another variable in the same scope and that bears the same name. Consider the following example:

#include <iostream> using namespace std;

int main() { double number = 3.14159; cout << "Number = " << number << "\n";

double number = 2.98; cout << "Number = " << number << "\n";

return 0; }

This would produce a "redefinition" error and the program would not compile, even if the second declaration uses a different data type. As one type of solution to this kind of problem, C++ allows you to create a "physical" scope. To do this, you can use curly brackets to delimit the scope of a particular variable. Here is an example:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

double number = 2.98; cout << "Number = " << number << "\n";

return 0; }

This would produce:


Number = 3.14159 Number = 2.98

In the code, notice that we delimit only the first declaration. Indeed, you can delimit each scope if you want:
#include <iostream> using namespace std;

int main() { { double number = 3.14159; cout << "Number = " << number << "\n"; }

{ double number = 2.98; cout << "Number = " << number << "\n"; }

return 0; }

Global Variables

C++ allows you to declare a variable outside of any function. Such as a variable is referred to as a global variable (). To declare a global variable, proceed as you normally would. Here is an example:
#include <iostream> using namespace std;

C++ Not

Some languag or Visual Basi variables. Som languages suc don't support t

double number;

int main() {

return 0; }

After declaring the variable, you can initialize it immediately:


#include <iostream> using namespace std;

double number = 3.14159;

int main() { cout << "Number = " << number << "\n";

return 0; }

You can also initialize it inside of the function that would use it. After declaring and initializing the variable, you can access its value and use it. For example, you can display its value to the user. Here is an example:
#include <iostream> using namespace std;

double number;

int main() { number = 3.14159;

cout << "Number = " << number << "\n";

return 0; }

In C++ (some other languages don't have this situation), the compiler always proceed in a top-down approach. After declaring a variable, only the sections under it can access it. This means that you cannot access a variable above its declaration. Consider the following program where only the area of the declaration has changed:
#include <iostream> using namespace std;

int main() { number = 3.14159;

cout << "Number = " << number << "\n";

return 0; }

double number;

This program would not compile. The reason is that, when accessing it inside of main(), as far as

main() is concerned, the variable has never been declared and C++ doesn't allow the use of a variable before it has been declared. Therefore, you must always declare a variable before accessing it. Namespaces Introduction 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 recognized. A namespace is not a variable. It is not a function. It is not a class. It is only a technique of naming a section of code and referring to that section of code with a name. Creating a namespace The syntax of creating a namespace is:
namespace Name { Body }

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 except that, throughout this site, the name of a namespace will start in uppercase. A namespace has 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; }

The entities included in the body of a namespace are referred to as its members. Accessing a namespace: The Scope Access Operator To access a member of a namespace, there are various techniques you can use. The scope access operator :: is used to access the members of a namespace. To do this, type the name of the namespace, followed by the scope access operator ::, followed by the member you are want to access. Only the members of a particular namespace are available when using its name. For example, to access the member a of the Mine namespace above, you can write:
Mine::a;

Once you have access to a namespace member, you can initialize it or display its value using cout.

Here is an example:
#include <iostream> using namespace std;

namespace Mine { int a; }

int main() { Mine::a = 140;

cout << "Value of a = " << Mine::a << endl; return 0; }

This would produce:


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> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { InterestAndDiscount::principal = 3250; InterestAndDiscount::rate = 0.1225; // =12.25% InterestAndDiscount::periods = 2;

cout << "Loan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: cout << "\nTime: endl; " << InterestAndDiscount::rate*100 << "%"; " << InterestAndDiscount::periods << " years" <<

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:
#include <iostream> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

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::periods;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: cout << "\nPeriods: << endl; " << InterestAndDiscount::rate << "%"; " << InterestAndDiscount::periods << " years"

return 0; }

Here is an example of running the program:


Interest and Discount Principal: $12500 Rate (example 8.75): 7.25 Number of Years: 10

Interest Calculation Principal: $12500.00 Rate: 7.25% Periods: 10 years

The member variable of a namespace can also be 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> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { double interest; double maturityValue;

cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> InterestAndDiscount::principal; cout << "Rate (example 8.75): "; cin >> InterestAndDiscount::rate; cout << "Number of Years: "; cin >> InterestAndDiscount::periods;

interest = InterestAndDiscount::principal * (InterestAndDiscount::rate/100) * InterestAndDiscount::periods; maturityValue = InterestAndDiscount::principal + interest;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << InterestAndDiscount::principal; cout << "\nRate: " << InterestAndDiscount::rate << "%";

cout << "\nPeriods:

" << InterestAndDiscount::periods << " years";

cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n";

return 0; }

The using Keyword The scope access operator ::provides a safe mechanism to access the members of a namespace. If the namespace is very long and the application needs constant access, this might be a little cumbersome. Another technique used to access the members of a namespace involves using two keywords: using and namespace. To call a namespace, on the section of the program where you need to access the members, type:
using namespace NamespaceName;

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> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; }

int main() { using namespace InterestAndDiscount; double interest; double maturityValue;

cout << "Interest and Discount\n"; cout << "Principal: $"; cin >> principal; cout << "Rate (example 8.75): "; cin >> rate; cout << "Number of Years: "; cin >> periods;

interest = principal * (rate/100) * periods; maturityValue = principal + interest;

cout << "\nLoan Processing"; cout << "\nPrincipal: $" << principal; cout << "\nRate: cout << "\nPeriods: " << rate << "%"; " << periods << " years";

cout << "\nInterest: $" << interest; cout << "\nMaturity Value: $" << maturityValue << "\n\n";

return 0; }

Here is an example of a result:


Interest and Discount Principal: $2500 Rate (example 8.75): 12.15 Number of Years: 4

Loan Processing

Principal: $2500 Rate: 12.15% Periods: 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. Combination of Namespaces Introduction Various namespaces can be part of the same file and the same application. You can create each namespace and specify its own members in its delimiting curly brackets. With various namespaces on the same file or application, you can have the same variables in different namespaces. Here is an example of two namespaces:
namespace InterestAndDiscount { double principal; double rate; int periods; 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> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods; 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::periods = 5; // Years InterestAndDiscount::discount = InterestAndDiscount::rate / 100; InterestAndDiscount::interest = InterestAndDiscount::principal * InterestAndDiscount::discount * InterestAndDiscount::periods; InterestAndDiscount::maturityValue = InterestAndDiscount::principal + InterestAndDiscount::interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << InterestAndDiscount::principal << "\nRate: " << InterestAndDiscount::rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << InterestAndDiscount::periods << " years" << "\nInterest: $" << InterestAndDiscount::interest << "\nMaturity Value: $" << InterestAndDiscount::maturityValue;

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;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice << "\nDiscount: $" << BuyAndSell::discountAmount << "\nTax Rate: " << BuyAndSell::taxRate << "\nTax Amount: $" << BuyAndSell::taxAmount << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n";

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> using namespace std;

namespace InterestAndDiscount { double principal; double rate; int periods;

double interest; double discount; double maturityValue; }

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

discount = rate / 100; interest = principal * discount * periods; maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: << "\nRate: << "\nDiscount: << "\nPeriods: $" << principal " << rate << "%" " << discount " << periods << " years"

<< "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue;

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

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> using namespace std;

namespace InterestAndDiscount {

double principal; double rate; int periods;

double interest; double discount; double maturityValue; }

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; }

int main() { { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

discount = rate / 100; interest = principal * discount * periods;

maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: << "\nRate: << "\nDiscount: << "\nPeriods: $" << principal " << rate << "%" " << discount " << periods << " years"

<< "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue; }

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

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 may want to qualify only the second discount call because the compiler will associate 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> using namespace std;

namespace InterestAndDiscount { . . . }

namespace BuyAndSell { . . . }

int main() { using namespace InterestAndDiscount; principal = 12500; // $ rate = 8.25; // % periods = 5; // Years

InterestAndDiscount::discount = Rate / 100; interest = principal * InterestAndDiscount::discount * periods;

maturityValue = principal + interest;

cout << "Interest Calculation"; cout << "\nPrincipal: $" << Principal << "\nRate: " << Rate << "%" << "\nDiscount: " << InterestAndDiscount::discount << "\nPeriods: " << periods << " years" << "\nInterest: $" << interest << "\nMaturity Value: $" << maturityValue;

using namespace BuyAndSell; originalPrice = 250; // $ taxRate = 16.00; // % BuyAndSell::discount = 20.00; // %

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * BuyAndSell::discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

cout << "\n\nBuy and Sell - Receipt"; cout << "\nOriginal Price: $" << originalPrice << "\nDiscount: $" << discountAmount << "\nTax Rate: " << taxRate << "\nTax Amount: $" << taxAmount << "\nNet Price: $" << netPrice << "\n\n";

return 0; }

Nesting Namespaces

Nesting a namespace is the ability to include a namespace inside (as part of the body) of another namespace. To do this, create the intended namespace as a member of the parent namespace. The nested namespace should have its own name and its own body. Here is an example:
namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; { long itemNumber; } }

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:
#include <iostream> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID {

long itemNumber; } }

int main() { BuyAndSell::originalPrice = 780.50; BuyAndSell::taxRate = 7.55; BuyAndSell::discount = 25; // % BuyAndSell::ItemID::itemNumber = 641238;

BuyAndSell::taxAmount = BuyAndSell::originalPrice * BuyAndSell::taxRate / 100; BuyAndSell::discountAmount = BuyAndSell::originalPrice * BuyAndSell::discount / 100; BuyAndSell::netPrice = BuyAndSell::originalPrice + BuyAndSell::taxAmount BuyAndSell::discountAmount;

cout << "Buy and Sell - Receipt"; cout << "\nItem Nunmber: " << BuyAndSell::ItemID::itemNumber; cout << "\nOriginal Price: $" << BuyAndSell::originalPrice; cout << "\nDiscount: $" << BuyAndSell::discountAmount; cout << "\nTax Rate: " << BuyAndSell::taxRate; cout << "\nTax Amount $" << BuyAndSell::taxAmount; cout << "\nNet Price: $" << BuyAndSell::netPrice << "\n\n";

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 as you want. Here is an example:
#include <iostream> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber; 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> using namespace std;

namespace BuyAndSell { double originalPrice; double taxRate; double taxAmount; double discount; double discountAmount; double netPrice; namespace ItemID { long itemNumber;

namespace DateSold { int month;

int day; int year; } } }

int main() { using namespace BuyAndSell; using namespace BuyAndSell::ItemID; using namespace BuyAndSell::ItemID::DateSold;

originalPrice = 780.50; taxRate = 7.55; discount = 25; // % itemNumber = 641238;

taxAmount = originalPrice * taxRate / 100; discountAmount = originalPrice * discount / 100; netPrice = originalPrice + taxAmount - discountAmount;

month = 10; day = 18; year = 2002;

cout << "Buy and Sell - Receipt"; cout << "\nReceipt Date: " << month << "/" << day << "/" << year; cout << "\nItem Nunmber: " << itemNumber; cout << "\nDiscount Category: " << qualifyForDiscount;

cout << "\nOriginal Price: $" << originalPrice; cout << "\nDiscount: $" << discountAmount; cout << "\nTax Rate: " << taxRate; cout << "\nTax Amount $" << taxAmount; cout << "\nNet Price: $" << netPrice << "\n\n";

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. The std Namespace To avoid name conflicts of the various items used in its own implementation, the C++ Standard provides a namespace called std. The std namespace includes a series of libraries that you will routinely and regularly use in your programs. The following libraries are part of the std namespace: algorithm bitset complex deque exception fstream functional iomanip ios iosfwd iostream istream iterator limits list locale map memory new numeric ostream queue set sstream stack stdexcept streambuf string typeinfo utility valarray vector

The following additional libraries can be used to include C header files into a C++ program: cassert cctype cerrno cfloat cios646 climits clocale cmath csetjmp csignal cstdarg cstddef cstdio cstdlib cstring ctime cwchar cwctype

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, simply type the name of the library as in iostream. Then, on the second line, type using namespace std; As an example, instead of typing

#include <iostream.h>

You can type:


#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. Operators and Operands

Unary Operators Introduction An operation is an action performed on one or more values either to modify the value held by one or both of the variables or to produce a new value by combining variables. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand. A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands. Unary Operators: The Positive Operator + Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + 1 2 3 4 5 6 +

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side. As a mathematical convention, when a value is positive, you do not need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore,

the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned as we learned in the previous lesson. To express a variable as positive or unsigned, you can just type it. here is an example:
#include <iostream> using namespace std;

int main() { int number = +802;

cout << "The value of the number is: " << number << "\n";

return 0; }

Unary Operators: The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left. Here is an example that uses two variables. One has a positive value while the other has a negative value:
#include <iostream> using namespace std;

int main() {

int number1 = 802; int number2 = -62;

cout << "The value of the first number is: " << number1 << "\n"; cout << "The value of the second number is: " << number2 << "\n";

return 0; }

Unary Operators: Increment and Decrement ++ and -The increment operator is used to increase the value of a number or variable by 1. The increment operator is performed with the ++ operator. Because it involves a few more other issues, we will study it later on. The decrement operator is used to decrease the value of a number or variable by 1. The decrement operator is performed with the -- operator. Because it involves a few more other issues, we will study it later on. Unary Operators: The Address Of Operator & In the previous lesson, we learned that, when declaring a variable, the compiler reserves an amount of space in memory for that variable. C++ provides an operator that can tell you where (the space for) a variable is located. This is done using the "address of" operator represented by the ampersand &. To get the address of a variable, use the ampersand operator on its left. The address is a hexadecimal number. Here is an example:
#include <iostream> using namespace std;

int main() { int number = 46;

cout << "\n&Number = " << &number;

return 0; }

This would produce:


&Number = 0012FED4

Unary Operators: The sizeof Operator We have already seen that when declaring a variable, the compiler reserves a portion of space in the computer memory to hold that variable. We also illustrated how much space some data types need to store their variable. C++ provides the unary sizeof operator that allows you to find out how much space a data type or a certain variable in your program is using. There are four methods you can use with the sizeof operator: using the variable or the data type. The general syntaxes of the sizeof operator are:
sizeof VariableName; sizeof DataType; sizeof(VariableName); sizeof(DataType);

Any of these four formulas is admissible. But it is good to refrain from using the data type except in rare cases that you can justify. The reason you should apply the sizeof operator on the variable is because, if you change the variable (the word variable means it can change throughout the program), that is, if you perform any operation on it, the sizeof operator will acknowledge that and render the right result. Some and most of the time, if you apply the sizeof operator on the data type, you might end up with a bug; if you are lucky, the program would simply not compile. Here is an example:
#include <iostream> using namespace std;

int main() { double period = 155.50; int sizeOf = sizeof Period;

cout << "The size of Period is " << sizeOf << " bytes\n\n";

return 0; }

Here is an example with various uses of the sizeof operator


// Use of the sizeof operator to find out how much // space a variable or an identifier are using #include <iostream> using namespace std;

int main() { char iChar; unsigned char uChar; signed char sChar; int iInt; short int sInt; unsigned int uInt; unsigned short int uShortInt; long int LInt; unsigned long int uLongInt; float iFloat; double iDouble; long double lDouble;

cout << "The sizeof operator used on a variable\n\n"; cout << "Identifier\t Memory Size\n"

<< "\t\t in Bytes\n"; cout << "----------------------------------"; cout << "\nchar\t\t\t" << sizeof(char); cout << "\nunsigned char\t\t" << sizeof(unsigned char); cout << "\nsigned char\t\t" << sizeof(signed char); cout << "\nint\t\t\t" << sizeof(int); cout << "\nshort int\t\t" << sizeof(short int); cout << "\nunsigned int\t\t" << sizeof(unsigned int); cout << "\nunsigned short int\t" << sizeof(unsigned short int); cout << "\nlong int\t\t" << sizeof(long int); cout << "\nunsigned long int\t" << sizeof(unsigned long int); cout << "\nfloat\t\t\t" << sizeof(float); cout << "\ndouble\t\t\t" << sizeof(double); cout << "\nlong double\t\t" << sizeof(long double);

cout << "\n\n";

return 0; }

This would produce:


The sizeof operator used on a variable

Identifier

Memory Size in Bytes

---------------------------------char unsigned char signed char 1 1 1

int short int unsigned int unsigned short int long int unsigned long int float double long double 8 8 4 2 4 4 2

While the previous example uses the name of data types, the following sizeof operators are used on the name of variables
// Use of the sizeof operator to find out how much // space a variable or an identifier are using #include <iostream> using namespace std;

int main() { char iChar; unsigned char uChar; signed char sChar; int iInt; short int sInt; unsigned int uInt; unsigned short int uShortInt; long int LInt; unsigned long int uLongInt; float iFloat; double iDouble;

long double lDouble;

cout << "The sizeof operator used on an identifier\n\n"; cout << "Identifier\t Memory Size\n" << "\t\t in Bytes\n"; cout << "------------------------------"; cout << "\nchar\t\t\t" << sizeof(iChar); cout << "\nunsigned char\t\t" << sizeof(uChar); cout << "\nsigned char\t\t" << sizeof(sChar); cout << "\nint\t\t\t" << sizeof(iInt); cout << "\nshort int\t\t" << sizeof(sInt); cout << "\nunsigned int\t\t" << sizeof(uInt); cout << "\nunsigned short int\t" << sizeof(uShortInt); cout << "\nlong int\t\t" << sizeof(LInt); cout << "\nunsigned long int\t" << sizeof(uLongInt); cout << "\nfloat\t\t\t" << sizeof(iFloat); cout << "\ndouble\t\t\t" << sizeof(iDouble); cout << "\nlong double\t\t" << sizeof(lDouble);

cout << "\n\n";

return 0; }

Algebraic Operators Introduction In algebra, operations are performed on numeric values. Algebraic operators are represented with the following symbols:

Practical Learning: Introducing Operators 1. Start your programming environment and create a new project named GCS2. Depending on your environment, if the file was not created already, then create a source file and save it as, or name it, exercise.cpp 2. Set the file's content as follows:
#include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; "; ";

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone;

cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty";

cout << "\n------------------------------------" << "\nShirts: << "\nPants: << "\nDresses: << "\nTies: << "\n\n"; " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts " << pants " << dresses " << ties

return 0; }

3. Execute the application and perform the exercise 4. Return to your programming environment The Addition The addition is an operation used to add one number to another. For example, if you have one pen and somebody gives you another pen, then you have two pens. If you keep receiving pens, you will soon have more than you had originally. In this manner, as you add pens, the number grows. The addition gives you to ability to add things of the same nature one to another, as many as necessary, until all items have been added. Sometimes, the items are added one group to another. The concept is still the same, except that this last example is faster. For example, if you have a group of eleven students and you add 5 students to the group, you can apply the same rule by adding one student at a time. But to perform this operation faster, you should work to add groups of items to one another. The addition is performed in mathematics using the + sign. The same sign is used in C++. The + sign is located on the left side of the Backspace key. You get it by pressing Shift and =. To get the addition of two values, you add the first one to the other. After the addition of two values has been performed, you get a new value. This means if you add Value1 to Value2, you would write Value1 + Value2. The result is another value we could call Value3. You can also add more than two values, like a + b + c. The order you use to add two or more values doesn't matter. This means Value1 + Value2 is the same

as Value2 + Value1. In the same way a + b + c is the same as a + c + b the same as b + a + c and the same as c + b + a. In C++, you can add values you know already, or you can use values the program gets from the user. The simplest way to add values in C++ is by performing a simple sum. Here is an example:
// Program used to get the sum of two values

#include <iostream> using namespace std;

iint main() { // Get the sum of two values cout << "244 + 835 = " << 244 + 835;

cout << "\n\n";

return 0; }

Here is the result:


244 + 835 = 1079

You can also add some values already declared and initialized in your program. Here is an example:
// Program used to get the sum of two initialized values #include <iostream> using namespace std;

int main() { int a = 244;

int b = 835;

// Get the sum of a and b cout << a << " + " << b << " = " << a + b; cout << "\n\n";

return 0; }

You can also get the values from the user as illustrated in the following program:
// Program used to get the sum of two initialized values #include <iostream> using namespace std;

int main() { int a, b, c;

// Get the sum of a, b, and c. cout << "\nType the first value: "; cin >> a; cout << "The second value: "; cin >> b; cout << "The last value: "; cin >> c;

cout << a << " + " << b << " + " << c << " = " << a + b + c << "\n\n";

return 0; }

Practical Learning: Using the Addition 1. To perform an addition, change the file as follows:

#include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; ";

cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; ";

totalItems = shirts + pants + dresses + ties;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------"

<< "\nItem Type

Unit Price Qty";

cout << "\n------------------------------------" << "\nShirts: << "\nPants: << "\nDresses: << "\nTies: " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts " << pants " << dresses " << ties;

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems << "\n\n";

return 0; }

2. Execute the application and process an order. Here is an example:

Order Month: 12 Order Year: 2002 Enter number of shirts: 12 Enter number of pants: 8 Enter number of dresses: 4 Enter number of ties: 6

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Alain Kounkou

Customer Phone: (240) 843-8220 Order Date: 12/12/2002 ------------------------------------

Item Type

Unit Price Qty

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 4 6 12 8

-----------------------------------Total Number of Items: 30

3. Return to your programming environment The Multiplication The multiplication allows adding one value to itself a certain number of times, set by a second value. As an example, instead of adding a value to itself in this manner: a + a + a + a, since the variable a is repeated over and over again, you could simply find out how many times a is added to itself, then multiply a by that number which, is this case, is 4. This would mean adding a to itself 4 times, and you would get the same result. The multiplication is performed with the * sign which is typed with Shift + 8. Just like the addition, the multiplication is associative: a * b * c = c * b * a. When it comes to programming syntax, the rules we learned with the addition operation also apply to the multiplication. Here is an example:
// Multiplication of multiple values #include <instream> using namespace std;

int main() { float a, b;

// Multiple of a and b. cout << "\nType two values: "; cin >> a >> b; cout << a << " * " << b << " = " << a * b; cout << "\n\n";

return 0; }

Practical Learning: Using the Multiplication 1. To perform a multiplication, change the file as follows:

#include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; "; ";

cout << "Enter number of ties: "; cin >> ties;

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants totalCostDresses totalCostTies

= shirts = pants

* priceShirts; * pricePants;

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

cout << "\n------------------------------------" << "\nShirts: " << totalCostShirts << "\nPants: << totalCostPants << "\nDresses: " << totalCostDresses << "\nTies: " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts << " " << pants << " " << dresses << " " << ties << " " << "

totalCostTies; cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\n";

return 0; }

2. Execute the application and process an order. Here is an example:

-=- Georgetown Cleaning Services -=Enter Customer Name: Patrice Keller

Enter Customer Phone: (703) 722-8814 Enter the date this order was placed Order Day: 10

Order Month: 12 Order Year: 2002 Enter number of shirts: 8 Enter number of pants: 8 Enter number of dresses: 5 Enter number of ties: 6

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Patrice Keller

Customer Phone: (703) 722-8814 Order Date: 12/10/2002

-----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 6 8 8 10 22 16.25 9.9

-----------------------------------Total Number of Items: 27

Total Cleaning of Items: 58.15

3. Return to your programming environment

The Subtraction The subtraction operation is used to take out or subtract a value from another value. It is essentially the opposite of the addition. The subtraction in C++ is performed with the - sign, which is between the 0 and the = keys. Here is an example:
// Subtraction of two values #include <iostream> using namespace std;

int main() { // Values used in this program int value1, value2, value3;

// Get the values from the user cout << "Type the first number: ";

cin >> value1; cout << "Type another number: "; cin >> value2;

// Subtract the first value from the second value3 = value1 - value2;

cout << value1 << " - " << value2 << " = " << value3 << "\n\n";

return 0; }

The following program shows the non-associativity of the subtraction operation:


// Non-associativity of the subtraction operation #include <iostream> using namespace std;

int main() { // Addition associativity cout << "128 + 42 + 5 = " << 128 + 42 + 5; cout << "\n5 + 42 + 128 = " << 5 + 42 + 128;

cout << "\n";

// Subtraction non-associativity cout << "\n128 - 42 - 5 = " << 128 - 42 - 5; cout << "\n5 - 42 - 128 = " << 5 - 42 - 128;

cout << "\n\n";

return 0; }

This would produce:


128 + 42 + 5 = 175 5 + 42 + 128 = 175

128 - 42 - 5 = 81 5 - 42 - 128 = -165

Notice that both operations of the addition convey the same result. In the subtraction section, the numbers follow the same order but a different operation; and the last two operations render different results. Practical Learning: Using the Subtraction 1. To apply a subtraction, change the file as follows:

#include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies = 1.65;

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning; double amountTended, difference;

int orderDay; int orderMonth; int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; "; ";

cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties;

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants totalCostDresses totalCostTies

= shirts = pants

* priceShirts; * pricePants;

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

cout << "The total order is: " << totalCostCleaning << "\n"; cout << "Amount Tended: "; cin >> amountTended; difference = amountTended - totalCostCleaning;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

cout << "\n------------------------------------" << "\nShirts: totalCostShirts << "\nPants: totalCostPants << "\nDresses: totalCostDresses << "\nTies: totalCostTies; " << priceShirts << " " << pricePants << " " << priceDresses << " " << priceTies << " " << shirts << " " << pants << " " << dresses << " " << ties << " " <<

" << " << "

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\nAmount Tended: << "\nDifference: " << amountTended " << difference << "\n";

return 0; }

2. Execute the application and process an order. Here is an example:

-=- Georgetown Cleaning Services -=Enter Customer Name: Raymond Lamont

Enter Customer Phone: (202) 888-0022 Enter the date this order was placed Order Day: 20

Order Month: 02

Order Year: 2002 Enter number of shirts: 5 Enter number of pants: 2 Enter number of dresses: 0 Enter number of ties: 4 The total order is: 18.35 Amount Tended: 20

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Raymond Lamont

Customer Phone: (202) 888-0022 Order Date: 2/20/2002 -----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 2 0 4 6.25 5.5 0 6.6

-----------------------------------Total Number of Items: 11

Total Cleaning of Items: 18.35 Amount Tended: Difference: 20 1.65

3. Return to your programming environment The Division Dividing an item means cutting it in pieces or fractions of a set value. For example, when you cut an apple in the middle, you are dividing it in 2 pieces. If you cut each one of the resulting pieces, you will get 4 pieces or fractions. This is considered that you have divided the apple in 4 parts. Therefore, the division is used to get the fraction of one number in terms of another. The division is performed with the forward slash /. When performing the division, be aware of its many rules. Never divide by zero (0). Make sure that you know the relationship(s) between the numbers involved in the operation. Here is an example:
// Program used to get half of a number. #include <iostream> using namespace std;

int main() { float a;

// Get a number from the user. cout << "\nType a number: "; cin >> a; cout << " Half of " << a << " is " << a / 2 << "\n\n";

return 0; }

Practical Learning: Using the Division 1. To divide a value, change the file as follows:

#include <iostream> using namespace std;

int main() { char customerName[60], customerPhone[20];

unsigned short shirts; unsigned short pants; unsigned short dresses; unsigned short ties; unsigned short totalItems;

double priceShirts double pricePants

= 1.25; = 2.75;

double priceDresses = 3.25; double priceTies double taxRate = 1.65; = 5.75; // 5.75%

double totalCostShirts, totalCostPants, totalCostDresses, totalCostTies; double totalCostCleaning; double amountTended, difference; double taxAmount, netPrice;

int orderDay; int orderMonth;

int orderYear;

cout << " -=- Georgetown Cleaning Services -=-\n"; cout << "Enter Customer Name: cin >> ws; cin.getline(customerName, 60); cout << "Enter Customer Phone: "; cin.getline(customerPhone, 20); cout << "Enter the date this order was placed\n"; cout << "Order Day: cin >> orderDay; cout << "Order Month: "; cin >> orderMonth; cout << "Order Year: "; cin >> orderYear; cout << "Enter number of shirts: "; cin >> shirts; cout << "Enter number of pants: "; cin >> pants; cout << "Enter number of dresses: "; cin >> dresses; cout << "Enter number of ties: "; cin >> ties; "; ";

totalItems = shirts + pants + dresses + ties;

totalCostShirts totalCostPants

= shirts = pants

* priceShirts; * pricePants;

totalCostDresses totalCostTies

= dresses * priceDresses; = ties * priceTies;

totalCostCleaning = totalCostShirts + totalCostPants + totalCostDresses + totalCostTies;

taxAmount netPrice

= totalCostCleaning * taxRate / 100; = totalCostCleaning + taxAmount;

cout << "The total order is: " << netPrice << "\n"; cout << "Amount Tended: "; cin >> amountTended;

difference = amountTended - netPrice;

cout << "\n===================================="; cout << "\n-=- Georgetown Cleaning Services -=-"; cout << "\n===================================="; cout << "\nCustomer Order"; cout << "\nCustomer Name: " << customerName;

cout << "\nCustomer Phone: " << customerPhone; cout << "\nOrder Date: " << orderMonth << '/' << orderDay << '/' << orderYear; cout << "\n------------------------------------" << "\nItem Type Unit Price Qty Sub-Total";

cout << "\n------------------------------------" << "\nShirts: " << totalCostShirts << "\nPants: " << totalCostPants " << priceShirts << " " << pricePants << " " << shirts << " " << pants << "

<< "\nDresses: << dresses << " << "\nTies: totalCostTies;

" << priceDresses << " " << totalCostDresses " << priceTies << "

"

" << ties << "

" <<

cout << "\n------------------------------------" << "\nTotal Number of Items: " << totalItems

<< "\nTotal Cleaning of Items: " << totalCostCleaning << "\nTax Rate: << "\nTax Amount: << "\nNet Price: << "\nAmount Tended: << "\nDifference: " << taxRate << "%" " << taxAmount " << netPrice " << amountTended " << difference << "\n";

return 0; }

2. Execute the application and perform an order. Here is an example:

-=- Georgetown Cleaning Services -=Enter Customer Name: Jeanne Lemarre

Enter Customer Phone: (410) 022-4209 Enter the date this order was placed Order Day: 04

Order Month: 08 Order Year: 2000 Enter number of shirts: 12 Enter number of pants: 8 Enter number of dresses: 5 Enter number of ties: 3

The total order is: 61.5465 Amount Tended: 100

==================================== -=- Georgetown Cleaning Services -===================================== Customer Order Customer Name: Jeanne Lemarre

Customer Phone: (410) 022-4209 Order Date: 8/4/2000 -----------------------------------Item Type Unit Price Qty Sub-Total

-----------------------------------Shirts: Pants: Dresses: Ties: 1.25 2.75 3.25 1.65 5 3 12 8 15 22 16.25 4.95

-----------------------------------Total Number of Items: 28

Total Cleaning of Items: 58.2 Tax Rate: Tax Amount: Net Price: Amount Tended: Difference: 100 38.4535 5.75% 3.3465 61.5465

3. Return to your programming environment

The Remainder

The division program above will give you a result of a number with decimal values if you type an odd number (like 147), which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result. Imagine you have 26 kids at a football (soccer) stadium and they are about to start. You know that you need 11 kids for each team to start. If the game starts with the right amount of players, how many will seat and wait? The remainder operation is performed with the percent sign (%) which is gotten from pressing Shift + 5. Here is an example:
// Program used to perform the remainder operation. #include <iostream> using namespace std;

int main() { int players = 26; int yourPlayers;

// When the game starts, how many players will wait?. cout << "\nOut of " << players << " players, " << 26 % 11 << " players will have to wait when the " << " football match starts.\n\n";

// Get the new number of players cout << "How many players do you have today? "; cin >> yourPlayers;

cout << "\nOut of " << yourPlayers << " players, " << yourPlayers % 11 << " players will not have a team " << " in the beginning.\n\n";

return 0; }

C++ Operators As a language, C++ is equipped with non-algebraic operators intended to perform specific operations. We will review some of these operators now; some others need intermediary concepts that we haven't studied and cannot study at this time. Parentheses Like most computer languages, C++ uses parentheses to isolate a group of items that must be considered as belonging to one entity. For example, as we will learn soon, parentheses allow a function to delimit the list of its arguments. Parentheses can also be used to isolate an operation or an expression with regard to another operation or expression. For example, when studying the algebraic operations, we saw that the subtraction is not associative and can lead to unpredictable results. In the same way, if your operation involves various operators such as addition(s) and subtraction(s), you can use parentheses to tell the compiler how to proceed with the operations, that is, what operation should (must) be performed first. Consider the following algebraic operation: 154 - 12 + 8 The question here is to know whether you want to subtract the addition of 12 and 8 from 154 or you want to add the difference between 154 and 12 to 8. Using parentheses, you can communique your intentions to the compiler. This is illustrated in the following program:
// Using parentheses #include <iostream> using namespace std;

int main() { cout << "(154 - 12) + 8 = " << (154 - 12) + 8 << "\n"; cout << "154 - (12 + 8) = " << 154 - (12 + 8) << "\n";

return 0; }

This would produce:


154 - 12) + 8 = 150

154 - (12 + 8) = 134

As you can see, using the parentheses controls how the whole operation would proceed This difference can be even more accentuated if your operation includes 3 or more operators and 4 or more operands. Square Brackets Square brackets are mostly used to control the dimension or index of an array. We will learn how to use them when we study arrays. Curly Brackets Curly brackets are probably the most used and the most tolerant operators of C++. Fundamentaly, curly brackets are used to create or isolate sections of code. As such they are required to delimit the bodies of functions, classes, structures, exceptions, and namespaces. They are also optionally used in conditional statements. Square brackets are also used to create variable scope. We will view all these uses of square brackets in this book. Incrementing a Number We are used to counting numbers such as 1, 2, 3, 4, etc. In reality, when counting such numbers, we are simply adding 1 to a number in order to get the next number in the range. C++ provides a technique of transparently counting such numbers. The simplest technique of incrementing a value consists of adding 1 to it. After adding 1, the value or the variable is (permanently) modified and the variable would hold the new value. This is illustrated in the following example:
#include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl;

value = value + 1; cout << "Value = " << value << endl;

return 0;

This would produce:


Value = 12 Value = 13

C++ provides a special operator that takes care of this operation. The operator is called the increment operator and is represented by ++. Instead of writing Value = Value + 1, you can write Value++ and you would get the same result. The above program can be re-written as follows:
#include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl; Value++; cout << "Value = " << value << endl;

return 0; }

The ++ is called a unary operator because it operates on only one variable. It is used to modify the value of the variable by adding 1 to it. Every time the Value++ is executed, the compiler takes the previous value of the variable, adds 1 to it, and the variable holds the incremented value:
#include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl; value++; cout << "Value = " << value << endl;

value++; cout << "Value = " << value << endl;

value++; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 12 Value = 13 Value = 14 Value = 15

Pre and Post-Increment When using the ++ operator, the position of the operator with regard to the variable it is modifying can be significant. To increment the value of the variable before re-using it, you should position the operator on the left of the variable:
#include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl;

cout << "Value = " << ++value << endl; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 12 Value = 13 Value = 13

When writing ++Value, the value of the variable is incremented before being called. On the other hand, if you want to first use a variable, then increment it, in other words, if you want to increment the variable after calling it, position the ++ operator on the right side of the variable:
#include <iostream> using namespace std;

int main() { int value = 12;

cout << "Value = " << value << endl; cout << "Value = " << value++ << endl; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 12 Value = 12 Value = 13

Decrementing Pre and Post-Decrementing

When counting numbers backward, such as 8, 7, 6, 5, etc, we are in fact subtracting 1 from a value in order to get the lesser value. This operation is referred to as decrementing a variable. This operation works as if a variable called Value has its value diminished by 1, as in Value = Value 1:
#include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; value = value - 1; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 8 Value = 7

As done to increment, C++ provides a quicker way of subtracting 1 from a variable. This is done using the decrement operation, that is --. To use the decrement operator, type on the left or the right side of the variable when this operation is desired. Using the decrement operator, the above program could be written:
#include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl;

value--; cout << "Value = " << value << endl;

return 0; }

Once again, the position of the operator can be important. If you want to decrement the variable before calling it, position the operator on the left side of the operand. This is illustrated in the following program:
#include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; cout << "Value = " << --value << endl; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 8 Value = 7 Value = 7

If you plan to decrement a variable only after it has been accessed, position the operator on the right side of the variable. Here is an example:
#include <iostream> using namespace std;

int main() { int value = 8;

cout << "Value = " << value << endl; cout << "Value = " << value-- << endl; cout << "Value = " << value << endl; }

This would produce:


Value = 8 Value = 8 Value = 7

Techniques of Incrementing and Decrementing a Variable It is not unusual to add or subtract a constant value to or from a variable. All you have to do is to declare another variable that would hold the new value. Here is an example:
#include <iostream> using namespace std;

int main() { double value = 12.75; double newValue;

cout << "Value = " << value << endl; newValue = value + 2.42; cout << "Value = " << newValue << endl;

return 0;

This would produce:


Value = 12.75 Value = 15.17

The above technique requires that you use an extra variable in your application. The advantage is that each value can hold its own value although the value of the second variable depends on whatever would happen to the original or source variable. Sometimes in your program you will not need to keep the original value of the source variable. You might want to simply permanently modify the value that a variable is holding. In this case you can perform the addition operation directly on the variable by adding the desired value to the variable. This operation modifies whatever value a variable is holding and does not need an additional variable. To add a value to a variable and change the value that the variable is holding, use the assignment = and the addition + operators to produce a new operator as += Here is an example:
#include <iostream> using namespace std;

int main() { double value = 12.75;

cout << "Value = " << value << endl; value += 4.42; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 12.75 Value = 17.17

To diminish the value of a variable, instead of the addition operation, use the subtraction and apply the same technique. In the above program, the variable can have its value decremented by applying the assignment and the subtraction operations on the variable. This is done with the -= operator. Here

is an example:
#include <iostream> using namespace std;

int main() { double value = 12.75;

cout << "Value = " << value << endl; value -= 4.42; cout << "Value = " << value << endl;

return 0; }

This would produce:


Value = 12.75 Value = 8.33

Operator Precedence and Direction When combining operations in C++, there are two aspects involved: an operator's precedence and its direction. If you ask a program to add two numbers, for example 240 + 65, the program will execute the operation by adding 240 to 65; in other words, it would read 240, then +, then 65, and evaluate the result. This is considered as operating from left to right: 240 -> + -> 65. On the other hand, if you ask the program to find the size of a variable, you would write sizeof(FirstName). In this case, the program would first consider the FirstName variable, then it would evaluate the size of that variable; in other words, it first finds out what the variable it is operating on, in this case FirstName. Once it knows the variable that is involved, it would execute the operation. This is considered that the operation is executed from right to left. This process is referred to as the direction of the operation. As you will regularly combine operators on your various calculations, each operation is known for how much it "weighs" as compared to other operators. This is known as its precedence. This means

that when a certain operator is combined with another, such as a + b * c, or x / y - z, some operators would execute before others, almost regardless of how you write the operation. That's why an operator could be categorized by its level of precedence.

Introduction to Functions

A Function as a Task Introduction A function is an assignment or a task that must be performed to complement the other part(s) of a program. There are two kinds of functions: those supplied to you and those you will be writing. The functions that are supplied to you are usually in three categories: those built-in the operating system, those written in C++ (they are part of the C++ language), and those supplied with your programming environment. The use of these functions is the same regardless of the means you get them; you should know what a function looks like, how to create one, what functions are already available, where they are located, and what a particular function does, how and when to use it. Function Declaration In order to create and use a function, you must let the compiler know. Letting the compiler know about your function means you declare it. The syntax of declaring a function is:
ReturnType FunctionName();

An assignment, considered a function, is made of three parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor. In later sections, we will review the possible return types available in C++. The simplest return type you can use is called, and represented as, void. Using this keyword, the simplest formula we can use is:
void FunctionName();

Function Names A function name follows the same rules we have applied to our variables so far except that, in our lessons, the name of a function will start in uppercase. In addition, use a name that specifies what the function is expected to do. Usually, a verb is appropriate for a function that performs an action. Examples of names of functions are Add, Start, Assign, Play, etc. If the assignment of a function is a combination of words, such as converting a temperature from Celsius to Fahrenheit, start the name of the function with a verb and append the necessary words each starting in uppercase (remember that the name of a function is in one word). Examples include ConvertToFahrenheit, CalculateArea, LoadFromFile, etc. Some functions will not include a verb. They

can simply represent a word such as Width, Index, New. They can also be a combination of words; examples include DefaultName, BeforeConstruction, or MethodOfAssignment. Function Definition Introduction In order to use a function in your program, you have to let the compiler know what the function does. To let the compiler know what the function is meant to do, you have to define it; which also means describing its behavior. The formula to define a function is:
void FunctionName() {Body}

You define a function using the rule we applied with the main() function. Define it starting with its return value (if none, use void), followed by the function name, its argument (if any) between parentheses, and the body of the function. Once you have defined a function, other functions can use it. Function Body As an assignment, a function has a body. The body of the function describes what the function is supposed to do. The body starts with an opening curly bracket { and ends with a closing curly bracket }. Everything between these two symbols belongs to the function. From what we have learned so far, here is an example:
void Message() {};

In the body of the function, you describe the assignment the function is supposed to perform. As simple as it looks, a function can be used to display a message. Here is an example:
void Message(){ cout << "This is C++ in its truest form.";}

A function can also implement a complete behavior. For example, on a program used to perform geometric shape calculations, you can use different functions to handle specific tasks. Imagine you want to calculate the area of a square. You can define a particular function that would request the side of the square:
cout << Enter the side of the square: ; cin >> Side;

and let the function calculate the area using the formula Area = Side * Side. Here is an example of such a function:
void SquareArea() { double Side; cout << "\nEnter the side of the square: ";

cin >> Side; cout << "\nSquare characteristics:"; cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side; }

Calling Functions One of the main reasons of using various functions in your program is to isolate assignments; this allows you to divide the jobs among different entities so that if something is going wrong, you might easily know where the problem is. Functions trust each other, so much that one function does not have to know HOW the other function performs its assignment. One function simply needs to know what the other function does, and what that other function needs. Once a function has been defined, other functions can use the result of its assignment. Imagine you define two functions A and B.

If Function A needs to use the result of Function B, function A has to use the name of function B. This means that Function A has to call Function B:

When calling one function from another function, provide neither the return value nor the body, simply type the name of the function and its list of arguments, if any. For example, to call a function named Welcome() from the main() function, simply type it, like this:
int main() { Message(); // Calling the Message() function return 0; }

The compiler treats the calling of a function depending on where the function is declared with regards to the caller. You can declare a function before calling it. Here is an example:
#include <iostream> using namespace std; void Message() {

cout << "This is C++ in its truest form."; } int main() { Message(); // Calling the Message() function return 0; }

Calling a Function Before Defining it The example we saw above requires that you define a function before calling it. C/C++, like many languages, allows you to call a function before defining it. Unlike many languages, in C++, when calling a function, the compiler must be aware of the function. This means that, you must at least declare a function before calling it. After calling the function, you can then define it as you see fit. Here is an example:
#include <iostream> using namespace std; int main() { void Message(); cout << "We will start with the student registration process."; Message(); // Calling the Message() function return 0; } void Message() { cout << "Welcome to the Red Oak High School."; }

To use any of the functions that ship with the compiler, first include the library in which the function is defined, then call the necessary function. Here is an example that calls the getchar() function:
#include <iostream> #include <cstdio> using namespace std; int main() { cout << "This is C++ in its truest form...\n\n"; getchar(); return 0; }

Returning a Value void Functions

A function that does not return a value is declared and defined as void. Here is an example:
void Introduction() { cout << "This program is used to calculate the areas of some shapes.\n" << "The first shape will be a square and the second, a rectangle.\n" << "You will be requested to provide the dimensions and the program " << "will calculate the areas"; }

Any function could be a void type as long as you are not expecting it to return a specific value. A void function with a more specific assignment could be used to calculate and display the area of a square. Here is an example:
void SquareArea() { double Side; cout << "\nEnter the side of the square: "; cin >> Side; cout << "\nSquare characteristics:"; cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side; }

When a function is of type void, it cannot be displayed on the same line with the cout extractor and it cannot be assigned to a variable (since it does not return a value). Therefore, a void function can only be called. The Type of Return Value The purpose of a function identifies what the function is meant to do. When a function has carried its assignment, it provides a result. For example, if a function is supposed to calculate the area of a square, the result would be the area of a square. The result of a function used to get a students first name would be a word representing a students first name. The result of a function is called a return value. A function is also said to return a value. There are two forms of expectations you will have from a function: a specific value or a simple assignment. If you want the function to perform an assignment without giving you back a result, such a function is qualified as void and would be declared as
void FunctionName();

A return value, if not void, can be any of the data types we have studied so far. This means that a function can return a char, an int, a float, a double, a bool, or a string. Here are examples of declaring functions by defining their return values:
double FunctionName();

char FunctionName(); bool FunctionName(); string FunctionName();

If you declare a function that is returning anything (a function that is not void), the compiler will need to know what value the function returns. The return value must be the same type declared. The value is set with the return keyword. If a function is declared as a char, make sure it returns a character (only one character). Here is an example:
char Answer() { char a; cout << "Do you consider yourself a reliable employee (y=Yes/n=No)? "; cin >> a; return a; }

A good function can also handle a complete assignment and only hand a valid value to other calling functions. Imagine you want to process members applications at a sports club. You can define a function that would request the first and last names; other functions that need a members full name would request it from such a function without worrying whether the name is complete. The following function is in charge of requesting both names. It returns a full name that any desired function can use:
string GetMemberName() { string FName, LName, FullName; cout << "New Member Registration.\n"; cout << "First Name: "; cin >> FName; cout << "Last Name: "; cin >> LName; FullName = FName + " " + LName; return FullName; }

The return value can also be an expression. Here is an example:


double SquareArea(double Side) { return (Side * Side); }

A return value could also be a variable that represents the result. Here is example:
double SquareArea(double Side) {

double Area; Area = Side * Side; return Area; }

If a function returns a value (other than void), a calling function can assign its result to a local variable like this:
Major = GetMajor();

Here is an example:
#include <iostream> using namespace std; int GetMajor() { int Choice; cout << "\n1 - Business Administration"; cout << "\n2 - History"; cout << "\n3 - Geography"; cout << "\n4 - Education"; cout << "\n5 - Computer Sciences"; cout << "\nYour Choice: "; cin >> Choice; return Choice; } int main() { int Major; cout << "Welcome to the student orientation program."; cout << "Select your desired major:"; Major = GetMajor(); cout << "You select " << Major; cout << "\n"; return 0; }

You can also directly display the result of a function using the cout operator. In this case, after typing cout and its << operator, type the function name and its arguments names, if any. So far, the compiler was displaying a warning because our main() function was not returning anything. In C++, a function should always display a return type, otherwise, make it void. If you declare a function without a return type, by default, the compiler considers that such a function should return an integer. Therefore, the main() function we have used so far should return an integer as follows:
#include <iostream>

using namespace std; int main() { cout << "This is C++ in its truest form...\n\n"; return 0; }

Strictly stated, the main() function can return any integer, which simply indicates that the program has ended. Returning 0 means that the program has terminated successfully. Since the main() function now returns an integer, you should indicate this on its declared line. A better version of the above main() function would be:
#include <iostream> using namespace std; int main() { cout << "This is C++ in its truest form...\n\n"; return 0; }

Arguments Parameters In order to carry its assignment, a function might be supplied something. For example, when a function is used to calculate the area of a square, you have to supply the side of the square, then the function will work from there. On the other hand, a function used to get a students first name may not have a need; its job would be to supply or return something. Some functions have needs and some do not. The needs of a function are provided between parentheses. These needs could be as varied as possible. If a function does not have a need, leave its parentheses empty. In some references, instead of leaving the parentheses empty, the programmer would write void. In this book, if a function does not have a need, we will leave its parentheses empty. Some functions will have only one need, some others will have many. A functions need is called an Argument. If a function has a lot of needs, these are its arguments. The argument is a valid variable and is defined by its data type and a name. For example, if a function is supposed to calculate the area of a square and it is expecting to receive the side of the square, you can declare it as double CalculateArea(double Side); A function used to get a students first name could be declared as:

string FirstName(); Here are examples of declaring functions; some take arguments, some dont:
double CalculateArea(double Side); char Answer(); void Message(float Distance); bool InTheBox(char Mine); string StudentName(); double RectangleArea(double Length, double Width); void DefaultBehavior(int Key, double Area, char MI, float Ter);

Techniques of Passing Arguments In order to perform its assignment, a function may need arguments. Any function that wants to use the result of another function must supply the other functions required arguments, if any. When declaring a function that uses arguments, specify each argument with a data type and a name. Passing Arguments by Value To use a function inside of another function, that is, to call a function from another function, specify the name of the function and its list of arguments (if any) inside of parentheses; only the name of each argument is needed. You can declare a function like this: float GetHours(string FullName); To call such a function from another, you would use: GetHours(FullName); Here is an example:
#include <iostream> #include <string> using namespace std; string GetName() { string FirstName, LastName, FN; cout << "Employee's First Name: "; cin >> FirstName; cout << "Employee's Last Name: "; cin >> LastName; FN = FirstName + " " + LastName; return FN; } int main() { string FullName; double Hours;

double GetHours(string FullName); FullName = GetName(); Hours = GetHours(FullName); cout << "\nEmployee's Name: " << FullName; cout << "\nWeekly Hours: " << Hours << " hours\n\n"; return 0; } double GetHours(string FullName) { double Mon, Tue, Wed, Thu, Fri, TotalHours; cout cout cout cout cout cout << << << << << << endl << FullName << "'s Weekly Hours\n"; "Monday: "; cin >> Mon; "Tuesday: "; cin >> Tue; "Wednesday: "; cin >> Wed; "Thursday: "; cin >> Thu; "Friday: "; cin >> Fri;

TotalHours = Mon + Tue + Wed + Thu + Fri; return TotalHours; }

Here is an example of running the program:


Employee's First Name: Frank Employee's Last Name: Dassault Frank Dassault's Weekly Hours Monday: 8.00 Tuesday: 8.50 Wednesday: 9.00 Thursday: 8.00 Friday: 8.00 Employee's Name: Frank Dassault Weekly Hours: 41.5 hours

When declaring a function, the compiler does not require that you supply a name for each argument, it only needs to know what type of argument(s) and how many arguments a function takes. This means that the GetHours() function could have been declared as
float GetHours(string);

Furthermore, the compiler does not care about the name you give an argument when declaring a function. Imagine you want to write a function that would calculate an items purchase price based on the items store price added the tax. The tax rate is a percentage value. This means that a tax rate set at 7.50% in C++ terms is equal to 0.075 (because 7.50/100 = 0.075). The tax amount collected on a

purchase is taken from an items price; its formula is: TaxRate Tax Amount = Item Price * 100 The formula of calculating the final price of an item is: Final Price = Item Price + Tax Amount Here is an example:
#include <iostream> using namespace std; int main() { double itemPrice, taxRate; double PurchasePrice(double itemPrice, double taxRate); cout << "Enter the price of the item: "; cin >> itemPrice; cout << "Enter the tax rate: "; cin >> taxRate; cout << "\nThe final price is: " << PurchasePrice(itemPrice, taxRate); cout << "\n\n"; return 0; } double PurchasePrice(double itemPrice, double taxRate) { double price; price = itemPrice + (itemPrice * taxRate / 100); return price; }

Here is an example of running the program:


Enter the price of the item: 125.95 Enter the tax rate: 5.75 The final price is: 133.192

Passing Arguments by Reference When you declare a variable in a program, the compiler reserves an amount of space for that variable. If you need to use that variable somewhere in your program, you call it and make use of its value. There are two major issues related to a variable: its value and its location in the memory.

The location of a variable in memory is referred to as its address. If you supply the argument using its name, the compiler only makes a copy of the arguments value and gives it to the calling function. Although the calling function receives the arguments value and can use in any way, it cannot (permanently) alter it. C++ allows a calling function to modify the value of a passed argument if you find it necessary. If you want the calling function to modify the value of a supplied argument and return the modified value, you should pass the argument using its reference. To pass an argument as a reference, when declaring the function, precede the argument name with an ampersand &. You can pass 0, one, or more arguments as reference in the program or pass all arguments as reference. The decision as to which argument(s) should be passed by value or by reference is based on whether or not you want the called function to modify the argument and permanently change its value. Here are examples of passing some arguments by reference:
void Area(double &side); // The argument is passed by reference bool Decision(char &answer, int age); // One argument is passed by reference // All arguments are passed by reference float Purchase(float &discountPrice, float &newDiscount, char &commission);

You add the ampersand when declaring a function and/or when defining it. When calling the function, supply only the name of the referenced argument(s). The above would be called with:
Area(side); Decision(answer, Age); Purchase(discountPrice, newDiscount, commission);

Imagine that you write a function that calculates employees weekly salary provided the total weekly hours and hourly rate. To illustrate our point, we will see how or whether one function can modify a salary of an employee who claims to have worked more than the program displays. The starting regular program would be as follows:
#include <iostream> using namespace std; int main() { float hours, rate, wage; void Earnings(float h, float r); cout << "Enter the total Weekly hours: "; cin >> hours; cout << "Enter the employee's hourly rate: ";

cin >> rate; cout cout cout cout cout << << << << << "\nIn the main() function,"; "\n\tWeekly Hours = " << hours; "\n\tSalary = $" << rate; "\n\tWeekly Salary: $" << hours * rate; "\nCalling the Earnings() function";

Earnings(hours, rate); cout << "\n\nAfter calling the Earnings() function, " << "in the main() function,"; cout << "\n\tWeekly Hours = " << hours; cout << "\n\tSalary = " << rate; cout << "\n\tWeekly Salary: " << hours * rate; return 0; } void Earnings(float thisWeek, float salary) { cout << "\n\nIn the Earnings() function,"; cout << "\n\tWeekly Hours = " << thisWeek; cout << "\n\tSalary = " << salary; cout << "\n\tWeekly Salary= " << thisWeek * Salary; }

If you test the program by typing 32 for the weekly hours and 6.45 for the salary, you would notice the weekly values are the same. Imagine that the employee claims to have worked 42 hours instead of the passed weekly hours. You could create the following function to find out.
void Earnings(float thisWeek, float salary) { thisWeek = 42; cout cout cout cout } << << << << "\n\nIn the "\n\tWeekly "\n\tSalary "\n\tWeekly Earnings() function,"; Hours = " << thisWeek; = " << salary; Salary= " << thisWeek * Salary;

If you test the program with a weekly hours value of 35.50 and a salary of 8.50, you would notice that the weekly salary is different inside of the Earnings() function but is kept the same in main(), before and after the Earnings() function. As an example of passing an argument by reference, you could modify the declaration of the Earnings() function inside of the main() function as follows:
void Earnings(float &h, float r);

If you want a calling function to modify the value of an argument, you should supply its reference

and not its value. You could change the function as follows:
void Earnings(float &thisWeek, float salary) { thisWeek = 42; cout cout cout cout } << << << << "\n\nIn the "\n\tWeekly "\n\tSalary "\n\tWeekly Earnings() function,"; Hours = " << thisWeek; = " << salary; Salary= " << thisWeek * Salary;

Default Arguments Whenever a function takes an argument, that argument is required. If the calling function does not provide the (required) argument, the compiler would throw an error. Imagine you write a function that will be used to calculate the final price of an item after discount. The function would need the discount rate in order to perform the calculation. Such a function could look like this:
double CalculateNetPrice(double discountRate) { double OrigPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); }

Since this function expects an argument, if you do not supply it, the following program would not compile:
#include <iostream> using namespace std; double CalculateNetPrice(double discountRate) { double origPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); } int main() { double finalPrice; double discount = 15; // That is 25% = 25 finalPrice = CalculateNetPrice(discount);

cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }

Most of the time, a function such as ours would use the same discount rate over and over again. Therefore, instead of supplying an argument all the time, C++ allows you to define an argument whose value would be used whenever the function is not provided with the argument. To give a default value to an argument, when declaring the function, type the name of the argument followed by the assignment operator =, followed by the default value. The CalculateNetPrice() function, with a default value, could be defined as:
#include <iostream> using namespace std; double CalculateNetPrice(double discountRate = 25) { double origPrice; cout << "Please enter the original price: "; cin >> origPrice; return origPrice - (origPrice * discountRate / 100); } int main() { double finalPrice; finalPrice = calculateNetPrice(); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }

If a function takes more than one argument, you can provide a default argument for each and select which ones would have default values. If you want all arguments to have default values, when defining the function, type each name followed by = followed by the desired value. Here is an example:
#include <iostream> using namespace std; double CalculateNetPrice(double tax = 5.75, double discount = 25, double origPrice = 245.55) { double discountValue = origPrice * discount / 100; double taxValue = tax / 100; double netPrice = origPrice - discountValue + taxValue;

cout << "Original Price: $" << origPrice << endl; cout << "Discount Rate: " << discount << "%" << endl; cout << "Tax Amount: $" << tax << endl; return netPrice; } int main() { double finalPrice; finalPrice = CalculateNetPrice(); cout << "Final Price: $" << finalPrice << "\n\n"; return 0; }

Here is the result produced:


Original Price: $245.55 Discount Rate: 25% Tax Amount: $5.75 Final Price: $184.22 Press any key to continue...

If a function receives more than one argument and you would like to provide default values for those parameters, the order of appearance of the arguments is very important.

If a function takes two arguments, you can declare it with default values. If you want to provide a default value for only one of the arguments, the argument that would have a default value must be the second in the list. Here is an example: double CalculatePrice(double Tax, double Discount = 25); When calling such a function, if you supply only one argument, the compiler would assign its value to the first parameter in the list and ignore assigning a value to the second (because the second already has a (default) value):
#include <iostream> using namespace std; double CalculateNetPrice(double tax, double discount = 25) { double origPrice; cout << "Enter the original price of the item: "; cin >> origPrice; double discountValue = origPrice * discount / 100; double taxValue = tax / 100;

double netPrice = origPrice - discountValue + taxValue; return NetPrice; } int main() { double taxRate = 5.50; // = 5.50% double finalPrice; finalPrice = CalculateNetPrice(taxRate); cout << "\nFinal Price = " << finalPrice << "\n\n"; return 0; }

Here is an example of running the program: Enter the original price of the item: 245.55Final Price = 184.218Press any key to continue... If you define the function and assign a default value to the first argument, if you provide only one argument when calling the function, you would receive an error.

If the function receives more than two arguments and you would like only some of those arguments to have default values, the arguments that would have default values must be at the end (right side) of the list. Regardless of how many arguments would or would not have default values, start the list of arguments without those that would not use default values.

Techniques of Using Functions Function Overloading A C++ program involves a great deal of names that represent variables and functions of various kinds. The compiler does not allow two variables to have the same name in the same function. Although two functions should have unique names in the same program, C++ allows you to use the same name for different functions of the same program following certain rules. The ability to have various functions with the same name in the same program is called function overloading. The most important rule about function overloading is to make sure that each one of these functions has a different number or different type(s) of arguments. The moment of inertia is the ability of of a beam to resist bending. It is calculated with regard to the cross section of the beam. Because it depends on the type of section of the beam, its calculation also depends on the type of section of the beam. In this exercise, we will review different formulas used to calculate the moment of inertia. Since this exercise is for demonstration purposes, you do not need to be a Science Engineering major to understand it.

Here is an example that calculates the moment of inertia with regard to the X axis:
#include <iostream> using namespace std; // Rectangle double MomentOfInertia(double b, double h) { return b * h * h * h / 3; } int main() { double Base, Height; cout << "Enter the dimensions of the Rectangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nMoment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm" << "\n\n"; return 0; }

Here are the formulas to calculate the moment of inertia for a semi-circle:

A circle, and thus a semi-circle, requires only a radius. Since the other version of the MomentOfInertia() function requires two arguments, we can overload it by providing only one argument, the radius. Here is an example that calculates the moment of inertia with regard to the X or base axis, overloading the MomentOfInertia() function as follows:
#include <iostream> using namespace std; // Rectangle double MomentOfInertia(double b, double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } int main() { double base, height, radius; cout << "Enter the dimensions of the Rectangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nMoment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm"; cout << "\n\nEnter the radius: "; cin >> radius; cout << "Moment of inertia of a semi-circle with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; return 0; }

Here are the formulas to calculate the moment of inertia of a triangle:

As you can see, the rectangle and the triangle are using the same dimension types. This means that we can provide only the same kinds of arguments, the base and the height, to calculate the moment of inertia. This also means C++ will not allow us to write two functions that have the same name, the same number of arguments, and the same types of arguments because that would violate the rule of function overloading. In order to overload the MomentOfInertia() function, we will add an argument that will never be used; this argument will serve only as a witness to set the difference between both versions of the function. This witness argument can be anything: an integer, a character, a string, a float, etc. For our example, we will make it a simple integer. To use the version applied to the triangle, we will provide this argument to overload the MomentOfInertia() function. When called with only two arguments, the rectangle version will apply. Here is an example that calculates the moment of inertia with regard to the X axis, overloading the MomentOfInertia function as follows:
#include <iostream> using namespace std; // Rectangle double MomentOfInertia(double b, double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } // Triangle double MomentOfInertia(double b, double h, int) { return b * h * h * h / 12; } int main() { double base = 7.74, height = 14.38, radius = 12.42; cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm\n\n"; cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; cout << "Enter the dimensions of the triangle\n"; cout << "Base: "; cin >> base; cout << "Height: "; cin >> height; cout << "\nTriangle\n" << "Moment of inertia with regard to the X

axis: "; cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n\n"; return 0; }

Inline Functions When you call a function B() from function A(), function A() sends a request and must get to Function B(). This is sometimes cumbersome for long functions. Whenever your program includes a small function, C++ allows you to include such a function where it is being called. When function B() calls function A(), instead of sending a request to function A(), the compiler would include a copy of function A() into function B() where it is being called. Such a function (function A()) is qualified inline. To create a function as inline, use the inline keyword when declaring the function as well as when defining it. Here is an example that makes use of an inline function:
#include <iostream> using namespace std; inline void Area(float Side) { cout << "The area of the square is " << Side * Side; } int main() { float s; cout << "Enter the side of the square: "; cin >> s; Area(s); return 0; }

Here is an example of running the program:


Enter the side of the square: 14.55 The area of the square is 211.702

You can also use the keyword on an inline function. To declare a function as inline and, type both words at the beginning of the declaration. The following program requests the hourly salary from the user. Then it calculates the periodic earnings:
#include <iostream> using namespace std; void inline RequestSalary(double& h); inline double Daily(double h); double inline Weekly(double h); inline double BiWeekly(double h); double inline Monthly(double h); double inline Yearly(double h);

int main() { double HourlySalary; cout << "This program allows you to evaluate your salary " << "for different periods\n"; RequestSalary(HourlySalary); cout << "\nBased on the hourly rate you supplied, here are your " << "periodic earnings"; cout << "\n\tHourly: $" << HourlySalary; cout << "\n\tDaily: $" << Daily(HourlySalary); cout << "\n\tWeekly: $" << Weekly(HourlySalary); cout << "\n\tBi-Weekly: $" << BiWeekly(HourlySalary); cout << "\n\tMonthly: $" << Monthly(HourlySalary); cout << "\n\tYearly: $" << Yearly(HourlySalary); cout << "\n\n"; return 0; } void inline RequestSalary(double& x) { cout << "Enter your hourly salary: $"; cin >> x; } inline double Daily(double x) { return x * 8; } double inline Weekly(double x) { return Daily(x) * 5; } inline double BiWeekly(double x) { return Weekly(x) * 2; } double inline Monthly(double x) { return Weekly(x) * 4; } double inline Yearly(double h) { return Monthly(h) * 12; }

Here is an example of running the program:

This program allows you to evaluate your salary for different periods Enter your hourly salary: $15.55 Based on the hourly rate you supplied, here are your periodic earnings Hourly: $15.55 Daily: $124.4 Weekly: $622 Bi-Weekly: $1244 Monthly: $2488 Yearly: $29856

Exploring Functions

Functions and their Arguments Constant Arguments When a function receives an argument, it performs one of two actions with regards to the value of the argument; it might modify the value itself or only use the argument to modify another argument or another of its own variables. If you know that the function is not supposed to alter the value of an argument, you should let the compiler know. This is a safeguard that serves at least two purposes. First, the compiler will make sure that the argument supplied stays intact; if the function tries to modify the argument, the compiler would throw an error, letting you know that an undesired operation took place. Second, this speeds up execution. To let the compiler know that the value of an argument must stay constant, use the const keyword before the data type of the argument. For example, if you declare a function like void Area(const string Side), the Area() function cannot modify the value of the Side argument. Consider a function that is supposed to calculate and return the perimeter of a rectangle if it receives the length and the width from another function, namely main(). Here is a program that would satisfy the operation (notice the Perimeter() function that takes two arguments):
#include <iostream> using namespace std; float Perimeter(float l, float w) { double p; p = 2 * (l + w); return p; } int main() { float length, width; cout << "Rectangle dimensions.\n"; cout << "Enter the length: "; cin >> length;

cout << "Enter the width: "; cin >> width; cout << "\nThe perimeter of the rectangle is: " << Perimeter(length, width) << "\n\n"; return 0; } This would produce: Rectangle dimensions. Enter the length: 35.55 Enter the width: 28.75 The perimeter of the rectangle is: 2044.12

As you can see, the Perimeter() function does not change the values of the length or the width. To reinforce the purpose of the assignment, you should make this clear to the compiler. To make the length and the width arguments constant, you would change the declaration of the Perimeter() function as follows:
float Perimeter(const float l, const float w);

You can make just one or more arguments constants, and there is no order on which arguments can be made constant. Practical Learning: Using Constant Arguments 1. Create a new project in a directory of folder called Constant Arguments 2. If necessary, create a source file. Save the source file as Main.cpp 3. To apply the "constantness" of arguments passed to functions, change the file as follows:

#include <iostream> using namespace std; // Rectangle double MomentOfInertia(const double b, const double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(const double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } // Triangle double MomentOfInertia(const double b, const double h, int) {

return b * h * h * h / 12; } int main() { double base = 7.74, height = 14.38, radius = 12.42; cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height) << "mm\n\n"; cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n"; cout << "Triangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(base, height, 1) << "mm\n"; return 0; }

4. Test the program:

Rectangle Moment of inertia with regard to the X axis: I = 7671.78mm Semi-Circle Moment of inertia with regard to the X axis: I = 9344.28mm Triangle Moment of inertia with regard to the X axis: I = 1917.95mm

5. To use a mix of functions, change the program as follows:

#include <iostream> using namespace std; // Rectangle double MomentOfInertia(const double b, const double h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(const double R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; }

// Triangle double MomentOfInertia(const double b, const double h, int) { return b * h * h * h / 12; } int main() { double double double double

length, height, radius; GetBase(); GetHeight(); GetRadius();

cout << "Enter the dimensions of the rectangle\n"; length = GetBase(); height = GetHeight(); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height) << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; radius = GetRadius(); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Radius) << "mm\n\n"; cout << "Enter the dimensions of the triangle\n"; length = GetBase(); height = GetHeight(); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height, 1) << "mm\n"; return 0; } double GetBase() { double b; cout << "Enter Base: "; cin >> b; return b; } double GetHeight() { double h; cout << "Enter Height: "; cin >> h; return h; }

double GetRadius() { double r; cout << "Enter Radius: "; cin >> r; return r; }

6. Test the program. Here is an example:

Enter the dimensions of the rectangle Enter Base: 18.25 Enter Height: 14.15 Rectangle Moment of inertia with regard to the X axis: I = 17235mm Enter the radius of the semi-circle Enter Radius: 15.55 Semi-Circle Moment of inertia with regard to the X axis: I = 22960.5mm Enter the dimensions of the triangle Enter Base: 16.35 Enter Height: 12.75 Triangle Moment of inertia with regard to the X axis: I = 2824.02mm

7. After examining the program, return to your programming environment An Argument as a Constant Reference If you pass an argument as reference, the compiler would access the argument from its location. The called function can modify the value of the argument. The advantage is that the code execution is faster because the argument gives access to its address. The disadvantage could be that if the calling function modifies the value of the argument, when the function exits, the value of the argument would have (permanently) changed and the original value would be lost (actually, this can be an advantage as we have learned in the passed). If you do not want the value of the passed argument to be modified, you should pass the argument as a constant reference. When doing this, the compiler would access the argument at its location (or address) but it would make sure that the value of the argument stays intact. To pass an argument as a constant reference, when declaring the function and when implementing it, type the const keyword, followed by the argument data type, followed by the ampersand operator, followed by a name for the argument. When declaring the function, the name of the argument is optional. Here is a function that receives an argument as a constant reference:
double CalculateNetPrice(const double& tax) {

double original; const double discount = 25; Original = GetOriginalPrice(); double discountValue = original * discount / 100; double taxValue = tax / 100; double netPrice = original - discountValue + taxValue; return NetPrice; }

You can mix arguments passed by value, those passed as reference, those passed by constant, and those passed by constant references. You will decide, based on your intentions, to apply whatever technique suits your scenario. The following program illustrates the use of various techniques of passing arguments:
#include <iostream> using namespace std; // Passing an argument by reference void GetOriginalPrice(double& originalPrice) { cout << "Enter the original price of the item: $"; cin >> originalPrice; } // Passing an argument as a constant reference // Passing arguments by value double CalculateNetPrice(const double& original, double tax, double discount) { discount = original * discount / 100; tax = tax / 100; double netPrice = original - discount + tax; return netPrice; } int main() { double taxRate = 5.50; // = 5.50% const double tiscount = 25; double price; double original; void Receipt(const double& orig, const double& taxation, const double& dis, const double& final); GetOriginalPrice(original); price = CalculateNetPrice(original, taxRate, discount); Receipt(original, taxRate, discount, price); cout << "\n\n"; return 0; }

void Receipt(const double& original, const double& tax, const double& discount, const double& finalPrice) { cout << "\nReceipt"; cout << "\nOriginal Price: $" << original; cout << "\nTax Rate: " << tax << "%"; cout << "\nDiscount Rate: " << discount << "%"; cout << "\nFinal Price: $" << finalPrice; }

Practical Learning: Passing Arguments by Constant References 1. To illustrate the passing of arguments by reference and by constant references, change the program as follows:

#include <iostream> using namespace std; // Rectangle double MomentOfInertia(const double& b, const double& h) { return b * h * h * h / 3; } // Semi-Circle double MomentOfInertia(const double& R) { const double PI = 3.14159; return R * R * R * R * PI/ 8; } // Triangle double MomentOfInertia(const double& b, const double& h, const int&) { return b * h * h * h / 12; } int main() { double length, height, radius; void GetBaseAndHeight(double&, double&); void GetRadius(double&); cout << "Enter the dimensions of the rectangle\n"; GetBaseAndHeight(length, height); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(length, height) << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; GetRadius(radius); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(radius) << "mm\n\n";

cout << "Enter the dimensions of the triangle\n"; GetBaseAndHeight(length, height); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(length, height, 1) << "mm\n"; cout << "\n\n"; return 0; } // Passing arguments by reference void GetBaseAndHeight(double& B, double& H) { cout << "Enter Base: "; cin >> B; cout << "Enter Height: "; cin >> H; } void GetRadius(double& R) { cout << "Enter Radius: "; cin >> R; }

2. Test the program. Here is an example:


Enter the dimensions of the rectangle Enter Base: 18.85 Enter Height: 15.55 Rectangle Moment of inertia with regard to the X axis: I = 23625.5mm Enter the radius of the semi-circle Enter Radius: 14.25 Semi-Circle Moment of inertia with regard to the X axis: I = 16192.7mm Enter the dimensions of the triangle Enter Base: 8.95 Enter Height: 11.25 Triangle Moment of inertia with regard to the X axis: I = 1061.94mm

3. After testing the program, return to your programming environment 4. To further mix the passing of arguments, change the program as follows:

#include <iostream> using namespace std;

// Rectangle // This function receives one argument by reference and two arguments // by constant references void MomentOfInertia(double& moment, const double& b, const double& h) { moment = b * h * h * h / 3; } // Semi-Circle // This function receives one argument by reference and one by // constant reference void MomentOfInertia(double& moment, const double& R) { const double PI = 3.14159; moment = R * R * R * R * PI/ 8; } // Triangle // This function receives one argument by reference, two arguments by // constant references and one argument by value void MomentOfInertia(double& moment, const double& b, const double& h, const int&) { moment = b * h * h * h / 12; } int main() { double length, height, radius, mRectangle, mSemiCircle, mTriangle; void GetBaseAndHeight(double&, double&); void GetRadius(double&); cout << "Enter the dimensions of the rectangle\n"; GetBaseAndHeight(length, height); MomentOfInertia(mRectangle, length, height); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mRectangle << "mm\n\n"; cout << "Enter the radius of the semi-circle\n"; GetRadius(radius); MomentOfInertia(mSemiCircle, radius); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mSemiCircle << "mm\n\n"; cout << "Enter the dimensions of the triangle\n"; GetBaseAndHeight(length, height); MomentOfInertia(mRectangle, length, height, 1); cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << mRectangle << "mm\n";

cout << "\n\n"; return 0; } // Passing arguments by reference void GetBaseAndHeight(double& b, double& h) { cout << "Enter Base: "; cin >> b; cout << "Enter Height: "; cin >> h; } void GetRadius(double& R) { cout << "Enter Radius: "; cin >> R; }

5. Test the program. Here is an example:

Enter the dimensions of the rectangle Enter Base: 12.85 Enter Height: 8.85 Rectangle Moment of inertia with regard to the X axis: I = 2969.01mm Enter the radius of the semi-circle Enter Radius: 5.55 Semi-Circle Moment of inertia with regard to the X axis: I = 372.59mm Enter the dimensions of the triangle Enter Base: 10.75 Enter Height: 6.75 Triangle Moment of inertia with regard to the X axis: I = 275.511mm

6. Return to your programming environment

Functions and Namespaces Functions Local Definition Like a variable, a function can be part of a namespace. To declare a function in a namespace, provide its return type, followed by a name, followed by the argument(s), if any, inside of parentheses. Here is an example:
namespace InterestAndDiscount

{ double double int double double double } Principal; Rate; Time; CalculateDiscount(); CalculateInterest(); CalculateMaturity();

A member function of a namespace can be accessed using the scope access operator. There are two main ways you can implement a member function. In the body of the namespace, which is a local implementation, delimit the body of the function with an opening curly bracket { and a closing curly bracket }. A function that is a member of a namespace has complete access to the member variables of the same namespace. Therefore, you do not have to pass the member variables as arguments to the member functions. Here is an example:
#include <iostream> using namespace std; namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate() { return Rate / 100; } double CalculateInterest() { return Principal * GetInterestRate() * Time; } double CalculateMaturity() { return Principal + CalculateInterest(); } } int main() { using namespace InterestAndDiscount; Principal = 12500; // $ Rate = 12.25; // % Time = 4; // Years cout << "Interest Calculation"; cout << "\nPrincipal: $" << Principal << "\nRate: " << Rate << "%" << "\nTime: " << Time << " years" << "\nInterest: $" << CalculateInterest() << "\nMaturity: $" << CalculateMaturity() << "\n\n"; return 0; } This would produce:

Interest Calculation Principal: $12500 Rate: 12.25% Time: 4 years Interest: $6125 Maturity: $18625

If a nested namespace has its own functions, you can also implement them in the body of the nested namespace. Here is an example:
namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate() { return Rate / 100; } double CalculateInterest() { return Principal * GetInterestRate() * Time; } double CalculateMaturity() { return Principal + CalculateInterest(); } namespace Discounter { double Maturity; double DiscountRate; double TermOfDiscount; double Discount() { return Maturity * DiscountRate * TermOfDiscount; } } }

After locally implementing the member functions of a nested namespace, you can access its members and display their value in the main() function as done above. Functions Global Definitions To implement a member function outside the body of a namespace, provide the return type, followed by the name of the namespace, followed by the scope access operator ::. Here is an example:
namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate(); double CalculateInterest(); double CalculateMaturity(); } InterestAndDiscount::GetInterestRate()

{ return Rate / 100; } InterestAndDiscount::CalculateInterest() { return Principal * GetInterestRate() * Time; } InterestAndDiscount::CalculateMaturity() { return Principal + CalculateInterest(); }

To implement the member functions of a nested namespace outside of the parent namespace, you must qualify each member function to specify the function (or the variable) you are calling. Here is an example:
namespace InterestAndDiscount { double Principal; double Rate; int Time; double GetInterestRate(); double CalculateInterest(); double CalculateMaturity() namespace Discounter { double Maturity; double DiscountRate; double TermOfDiscount; double Discount(); } } . . . InterestAndDiscount::Discounter::Discount() { return Maturity * DiscountRate * TermOfDiscount; }

Namespaces and External Functions The member variables of a namespace are variables like any of those we have used so far. They can request their values from an outside function. Here is an example:
#include <iostream> using namespace std; namespace InterestAndDiscount { . . . } . . . int main() { using namespace InterestAndDiscount;

double GetThePrincipal(); cout << "Loan Processing\n"; cout << "Enter the following values\n"; Principal = GetThePrincipal(); cout << "Rate (between 0 and 100): "; cin >> Rate; cout << "Time (number of years): "; cin >> Time; cout cout cout cout cout cout } double GetThePrincipal() { double P; cout << "Principal: $"; cin >> P; return P; } << << << << << << "\nInterest on a loan"; "\nPrincipal: $" << Principal; "\nRate: " << Rate << "%"; "\nTime: " << Time << " years"; "\nInterest: $" << CalcInterest(); "\nMaturity Value: $" << CalcMaturityValue();

return 0;

The member variable of a namespace can also be passed as argument to a function. When passing the argument, if the using namespace routine has been entered, you can pass the argument like any other. Otherwise, you should qualify the namespace member with the :: operator. In the following example, one member of a namespace is passed by its name only because of the previous using namespace. The other members are passed by being qualified, which is for demonstration purposes only:
#include <iostream> using namespace std; namespace InterestAndDiscount { . . . } . . . int main() { using namespace InterestAndDiscount; void GetThePrincipal(double& p); void RateAndTime(double &r, double &t); cout << "Loan Processing"; cout << "\nEnter the following values\n"; GetThePrincipal(Principal);

RateAndTime(InterestAndDiscount::Rate, InterestAndDiscount::Time); cout cout cout cout cout cout cout cout cout } void GetThePrincipal(double& P) { cout << "Principal: $"; cin >> P; while( P < 0 ) { cout << "Enter a positive number: $"; cin >> P; } } void RateAndTime(double &rate, double &time) { do { cout << "Rate (between 0 and 100): "; cin >> rate; } while(rate < 0 || rate > 100); do { cout << "Time (Nbr of Years): "; cin >> time; } while(time <= 0 || time >= 30); } << << << << << << << << << setiosflags(ios::fixed) << setprecision(2); "\nInterest on a loan"; "\nPrincipal: $" << Principal; "\nRate: " << Rate << "%"; setiosflags(ios::fixed) << setprecision(0); "\nTime: " << Time << " years"; setiosflags(ios::fixed) << setprecision(2); "\nInterest: $" << CalcInterest(); "\nMaturity Value: $" << CalcMaturityValue();

return 0;

C++ Built-in Functions Introduction Although as a smart programmer you can create any function to perform a desired job, the C++ language provides a series of functions already made so you can just add them to your program without caring how they work, all you need to know is what these functions do. The functions that are part of the C++ language are highly valuable, were tested sufficiently, and are completely reliable. The C++ built-in functions are made for various assignments ranging from algebra, geometry, trigonometry, and finance, etc. Besides the functions that are part of the C++ Standard, each compiler ships with its own set of functions that may not be available on other compilers. Borland C++ Builder provides an extremely rich library of functions. Asserting a Value or an Expression

Most of the values you use in your program will need to fit in an interval of your choice. For example, when requesting the age of a person, you would need such a value to be positive. After all, you do not expect a person to be 26 years old. C++ provides a function that can be used to check that a value or expression responds to a criteria of your choice. This function is called assert() and is defined in the cassert library of the std namespace. Its syntax is:
void assert(int Expression);

The assert() function considers an expression as its argument and tests it. This function is used in the same context as the conditional statements we will study in the next lesson of this book. If the Expression is true, assert() acknowledges that and lets the compiler continue with the next operation. If the Expression is false, assert() displays a (nasty) message. Although we have not yet learned conditional statements, the following is an example that requests the age of a student and checks that the supplied age is valid only if the student is older than 8:
#include <iostream> #include <cassert> using namespace std; int main() { float StudentAge; cout << "Type Student's Age: "; cin >> StudentAge; assert(StudentAge > 8); cout << "Student Age: " << StudentAge << "\n\n"; return 0; }

Mathematic Functions The C++ language also provides a series of functions to perform various mathematically related operations. The functions are defined in various libraries and this can depend on the compiler you are using. The functions defined in the cmath library are: acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp ldexp log log10 modf pow sin sinh sqrt tan tanh

Additional functions are defined in the cstdlib library and they are: abs div labs ldiv srand rand

C++ Projects and Linkage C++ and Files Introduction A computer application is primarily a series of files put together to compose a single entity. With previous generations of programming, you had to create text files, save them with a .c, a .cc, or a .cpp extension, link them and compile them. Many modern programming environments allow you to create the files and hand them to the compiler that would link them as a project, and then create an executable. In reality, the process has not changed, it has only been made easier and faster. Still, because the programming environments are developed by different companies, each presents its own way of creating the necessary files, compiling them, and creating an executable. When writing a program, the main reason for using functions is to isolate assignments. This allows you to effectively troubleshoot problems when they arise (because they will arise, not if but when). For example, if you are asked to write a program that would process orders at a department store, you can write one long main() function that would process all requests and orders. When the store is having a sale and you need to apply a discount to the program, you would spend time looking for the sections that use the discount and calculate the price. If you use functions to isolate assignments, you can easily find out which particular function deals with discount; all you would have to do is change the discount value without having to read the whole program. Practical Learning: Creating a File 1. Start a new project in your programming environment and name it MomentOfInertia1 2. If necessary, create a new source file. Save the current source file as Exercise.cpp Header Files When using functions in a program, we found out that the order of declaring functions was important. For example, you cannot call a function that has not been declared yet. For this reason, whenever you need to call a function, you should find out where it was created or whether it has been declared already. If the program is using many functions, it would become cumbersome to start looking for functions. At the same time, on a large program, it is usual for many functions to use the same kind of variable. Although you can locally declare the same variable needed by a function, if these functions of the same program would need to exchange values among them, you should declare some variables globally, usually on top of the file, then make such a variable available to any function that needs it. To make these functions and variables easily manageable, you can create one file where you would list the functions and variables used in a program. Such a file is called a header file and it has the h extension.

File Preprocessors As you are creating header files, if you work with a large team, you should avoid including in your program a file that has already been included. C++ allows you to avoid this by asking the compiler to check whether a header or a section of code has already been included in your program. This checking is performed using objects called preprocessors. When using preprocessors to check whether a section of code or a file has already been included in your program, you start the file or the section with
#ifndef WhatToCheck

The preprocessors must start with the # symbol as we have been using on the #include preprocessor so far. The ifndef preprocessor, word for word, means If Not Defined. It refers to the word on its right side to check if that word has already been included. Because the #ifndef is used to check If WhatToCheck has not been defined yet, it can also be written as
#if !define WhatToCheck

Both would mean the same. In reality, what you would be asking this preprocessor to do is to check if the WhatToCheck word has not already been included. If it has not, then you would ask the compiler to define this section of code with the WhatToCheck word. To do this, you would decide that the section of code you want to delimit will be referred to with the WhatToCheck word. Therefore, the #ifndef preprocessor is followed by a
#define WhatToCheck

This means that if WhatToCheck has not been included yet, then it would be defined starting with the #define. The section must end with the #endif preprocessor. This time, you do not need to specify what needs to be ended; the compiler will figure that out. Source Files After creating the header file, you can create another file to define the functions. The file used to implement the functions of the header file is called the Source File and it has a cpp extension. In order to use the code that is written in the header file, you must specify its file using the #include preprocessor and including the name of the file in double-quotes. The process of creating header and source files depends on your programming environment. Practical Learning: Creating a Header File: KDevelop 1. To create a header file, on the main menu, click File -> New

2. On the New File dialog box, in the General tab, click C/C++ Header (*.h,*.hxx) and, in the Filename edit box, type Inertia

3. Make sure that the Add To Project check box is checked and click OK

Practical Learning: Creating a Header File: Borland C++BuilderX 1. On the main menu, click File -> New File... 2. In the Create New File dialog box, set the Name to Inertia 3. In the Type combo box, select h

4. Click OK

Practical Learning: Creating a Header File: Borland C++ Builder 6 1. To create a header file, from the main menu of Borland C++ Builder, click File -> New -> Other 2. From the New Items dialog box, click Header File

3. Click OK By default, the first header file of C++ Builder is named File1.h and the subsequent names are incremental. If you want to change the name of the file, you must save it and give it the desired name 4. Save the file as Inertia.h

Practical Learning: Creating a Header File: Microsoft Visual C++ 1. To create a header file in Microsoft Visual C++ 5 and 6, on the main menu, click File -> New 2. From the Files property page of the New dialog box, click C/C++ Header FileType a name in the File Name edit box as Inertia 3. Click OK

Practical Learning: Creating a Header File: Dev-C++ 1. To create a header file in Dev-C++, on the main menu, click File -> New Source File 2. On the main menu, click File -> Save Unit 3. In the Save File dialog box, change the File As Type combo box to Header File (.h) and type the desired name of the file in the File Name text box as Inertia

4. Click Save

Practical Learning: Creating a Header File: Microsoft Visual C++ .Net 1. To create a header file in Microsoft Visual C++ .Net, on the main menu, click Project -> Add New Item 2. In the Add New Item dialog box, make sure the Visual C++ node is selected in the Categories tree view. In the Templates, click Header File 3. In the Name text box, type Inertia 4. Click Open

In all cases, replace the contents of the file with the following:

#ifndef _INERTIA_H_ #define _INERTIA_H_

double MomentOfInertia(const double b, const double h); double MomentOfInertia(const double R); double MomentOfInertia(const double b, const double h, const int); double GetBase(); double GetHeight(); double GetRadius();

#endif // INERTIA_H_

Source Files A source file is used to actually define the behavior of an object. This is also referred to as implementing the object. The creation of a source file also depends on the programming environment. Practical Learning: Creating a Source File: Borland C++ BuilderX 1. On the main menu, click File -> New File... 2. In the Create New File dialog box, set the Name to Inertia

3. In the Type combo box, select cpp

4. Click OK Practical Learning: Creating a Source File: KDevelop 1. To create a source file, on the main menu, click File -> New 2. In the New File dialog box, click C/C++ File (*.cpp,*.c,*.cc,*.C ) 3. In the Filename edit box, type Inertia 4. Make sure that the the Add To Project check box is selected and click OK

Practical Learning: Creating a Source File: Borland C++ Builder 1. To create a source file, from the main menu of Borland C++ Builder, click File -> New -> Other 2. From the New Items dialog box, click Cpp File 3. Click OK 4. Save the file as as Inertia.cpp

Practical Learning: Creating a Source File: Microsoft Visual C++ 1. To create a source file in Microsoft Visual C++ 5 and 6, on the main menu, click File -> New 2. From the Files property page of the New dialog box, click C++ Source File 3. Type a name in the File Name edit box 4. Click OK

Practical Learning: Creating a Source File: Dev-C++ 1. To create a header file in Dev-C++, on the main menu, click File -> New Source File 2. On the main menu, click File -> Save Unit 3. In the Save File dialog box, make sure the File As Type combo box displays C++ Source File (.cpp). Type the desired name of the file in the File Name text box as Inertia.cpp (either make sure that the dialog box does not add the .h extension or append the .cpp extension):

4. Click Save

Practical Learning: Creating a Source File: Microsoft Visual C++ .Net 1. To create a source file in Microsoft Visual C++ .Net, on the main menu, click Project -> Add New Item 2. In the Add New Item dialog box, make sure the Visual C++ node is selected in the Categories tree view. In the Templates, click C++ File (.cpp) (it should be selected by default 3. In the Name text box, type Inertia as the name of the file and click Open

In all cases, replace the contents of the file with the following:

#include <iostream> using namespace std;

#include "Inertia.h"

// Rectangle double MomentOfInertia(const double b, const double h) { return b * h * h * h / 3; }

// Semi-Circle double MomentOfInertia(const double r) { const double PI = 3.14159; return r * r * r * r * PI/ 8; }

// Triangle double MomentOfInertia(const double b, const double h, const int)

{ return b * h * h * h / 12; }

double GetBase() { double b;

cout << "Base: "; cin >> b;

return b; }

double GetHeight() { double h;

cout << "Height: "; cin >> h;

return h; }

double GetRadius() { double r;

cout << "Radius: "; cin >> r;

return r; }

1. To prepare the application for a test, in the Main.cpp file, type the following:

#include <iostream> #include <string> using namespace std;

#include "Inertia.h"

void Announce(const string Figure) { cout << "Enter the dimensions of the " << Figure << "\n"; }

int main() { double Length, Height, Radius;

Announce("rectangle"); Length = GetBase(); Height = GetHeight(); cout << "Rectangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height) << "mm\n\n";

Announce("semi-circle"); Radius = GetRadius(); cout << "Semi-Circle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Radius) << "mm\n\n";

Announce("triangle"); Length = GetBase(); Height = GetHeight();

cout << "\nTriangle\n" << "Moment of inertia with regard to the X axis: "; cout << "I = " << MomentOfInertia(Length, Height, 1) << "mm\n";

return 0; }

2. Save the project and test it. Here is an example

Variable External Linkage We saw that you could use different files in the same program. In our header files, we declared only functions. In many cases, you can also declare one or more variables in a (header) file and want to access such a variable in another file. After declaring a variable in one file, you can access it in any other file. This process is referred to as external linkage. To perform external linkage with a variable, in most cases, there is not much to do: you simply declare and optionally initialize a variable in one file, #include that file in another file, and use the variable as you see fit. Consider the following example: Header File: Exercise.h
#ifndef Exercise_H #define Exercise_H

int numberOfPagesInTheBook = 842;

#endif // Exercise_H

Source File: Exercise.cpp


#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { cout << "This book contains " << numberOfPagesInTheBook << " pages"; return 0; }

This would produce:


This book contains 842 pages

Imagine that, before accessing such a variable, you declare another variable of the same data type and the same name. Consider the following example: Header File: Exercise.h
#ifndef Exercise_H #define Exercise_H int numberOfPagesInTheBook = 842; #endif // Exercise_H

Source File: Exercise.cpp


#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { int numberOfPagesInTheBook; cout << "This book contains " << numberOfPagesInTheBook << " pages"; return 0;

Since a file included, in this case Exercise.h, has a variable with the same name as a locally declared variable, when you try accessing it locally, the compiler would consider the local variable and would ignore the external variable. The above code would produce:
This book contains 8856072 pages

(This result is from Borland C++BuilderX) To indicate that the newly declared variable is simply a reference to the external variable, when redeclaring it, start the declaration with the extern keyword:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> #include "Exercise.h" using namespace std; int main( int argc, char * argv[] ) { extern int numberOfPagesInTheBook; cout << "This book contains " << numberOfPagesInTheBook << " pages"; return 0; }

This time, it is the external variable that will be accessed. References Referenced Variables A reference is a variable name that is a duplicate of an existing variable. It provides a technique of creating more than one name to designate the same variable. To declare a reference variable, you use the reference operator expressed with the ampersand. The syntax of creating or declaring a reference is:
DataType &RefernceName = VariableName;

To declare a reference, type the variables name preceded by the same type as the variable it is referring to. Between the data type and the reference name, type the ampersand operator &. To specify what variable the reference is addressed to, use the assignment operator = followed by the name of the variable. The referred to variable must exist already. You cannot declare a reference as:
int &mine;

The compiler must know what variable you are referring to. Here is an example:
#include <iostream> using namespace std; int main() { int number = 228; int &nbr = number; return 0; }

The ampersand operator between the data type and the variable name can assume one of three positions as follows:
int& nbr; int & nbr; int &nbr;

As long as the & symbol is between a valid data type and a variable name, the compiler knows that the variable name (in this case Nbr) is a reference. Once a reference has been initialized, it holds the same value as the variable it is referring to. You can then display the value of the variable using either of both:
#include <iostream> using namespace std; int main() { int number = 228; int & nbr = number; cout << "Number = " << number << "\n"; cout << "Its reference = " << nbr << "\n\n"; return 0; }

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream> using namespace std;

int main() { int number = 228; // Regular variable int& nbr = number; // Reference cout << "Number = " << number << "\n"; cout << "Its reference = " << nbr << "\n"; // Changing the value of the original variable number = 4250; cout << "\nNumber = " << number; cout << "\nIts reference = " << nbr << "\n"; // Modifying the value of the reference Nbr = 38570; cout << "\nNumber = " << number; cout << "\nIts reference = " << nbr << "\n\n"; return 0; }

In the same way, you can use either a reference or the variable it is referring to, to request the variables value from the user. Here is an example:
#include <iostream> using namespace std; int main() { double price; double& refPrice = price; cout << "What's the price? $"; cin >> price; cout << "Price = $" << price << "\n"; cout << "Same as: $" << refPrice << "\n\n"; cout << "What's the price? $"; cin >> refPrice; cout << "Price = $" << price << "\n"; cout << "Same as: $" << refPrice << "\n"; return 0; }

If you change the value of the variable, the compiler updates the value of the reference so that both variables would hold the same value. In the same way, you can modify the value of the reference, which would update the value of the referred to variable. To access the reference, do not use the ampersand operator; just the name of the reference is sufficient to the compiler. This is illustrated in the following:
#include <iostream> using namespace std;

main() { int Number = 228; // Regular variable int& Nbr = Number; // Reference cout << "Number = " << Number << "\n"; cout << "Its reference = " << Nbr << "\n"; // Changing the value of the original variable Number = 4250; cout << "\nNumber = " << Number; cout << "\nIts reference = " << Nbr << "\n"; // Modifying the value of the reference Nbr = 38570; cout << "\nNumber = " << Number; cout << "\nIts reference = " << Nbr << "\n\n"; }

In the way, you can use either a reference or the variable it is referring to, to request the variables value from the user. Here is an example:
#include <iostream> using namespace std; main() { double Price; double& RefPrice = Price; cout << "What's the price? $"; cin >> Price; cout << "Price = $" << Price << "\n"; cout << "Same as: $" << RefPrice << "\n\n"; cout << "What's the price? $"; cin >> RefPrice; cout << "Price = $" << Price << "\n"; cout << "Same as: $" << RefPrice << "\n"; }

Referenced Functions A function can be made to return a reference to a value. When defining such a function, make sure you type the reference operator to its left. After processing the function in its body, you must make sure you return a value that is a reference of the same type of the function. Here is an example:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> using namespace std;

int &GetNumberOfPages() { int pp = 842; int &pages = pp; return pages; } int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; return 0; }

If the function is not modifying any value it may have received, you can declare it as a constant:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> using namespace std; const int &GetNumberOfPages() { int pp = 842; int &pages = pp; return pages; } int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; return 0; }

Static Variables and Functions Static Variables Consider the following program:
#include <iostream> using namespace std; void Starter(int y) { double a = 112.50; double b = 175.25; a = a / y; b = b + 2;

cout cout cout cout }

<< << << <<

"y "a "b "b

= = = /

" " " a

<< y << endl; << a << endl; << b << endl; = " << b / a << "\n\n";

int main() { Starter(2); Starter(2); Starter(2); Starter(2); return 0; }

When executed, this program would produce:


y a b b y a b b y a b b y a b b = = = / = = = / = = = / = = = / 2 56.25 177.25 a = 3.15111 2 56.25 177.25 a = 3.15111 2 56.25 177.25 a = 3.15111 2 56.25 177.25 a = 3.15111

The Starter() function receives one argument passed when it is called. The called function also receives the same argument every time. Looking at the result, the argument passed to the function and the local variables declared inside of the called function keep the same value every time the function is called. That is, when the Starter() function is exited, the values remain the same. We know that, when a function is defined, any variable declared locally belongs to the function and its influence cannot expand beyond the body of the function. If you want a locally declared variable to keep its changed value when its host function is exited, declare such a variable as static. To declare a static variable, type the static keyword on the left of the variables data type. For example, if you plan to declare a Radius variable as static in an Area() function, you could write:
double Area() { static double Radius; }

When you declare a variable as static, it is initialized with a 0 value. Otherwise, you can initialize it

with a value of your choice when declaring it. To make the local variables of our Starter() function static, we can declare them as follows:
void Starter(int y) { static double a = 112.50; static double b = 175.25; a = a / y; b = b + 2; cout cout cout cout } << << << << "y "a "b "b = = = / " " " a << y << endl; << a << endl; << b << endl; = " << b / a << "\n\n";

This time, when executing the program, it would produce:


y a b b y a b b y a b b y a b b = = = / = = = / = = = / = = = / 2 56.25 177.25 a = 3.15111 2 28.125 179.25 a = 6.37333 2 14.0625 181.25 a = 12.8889 2 7.03125 183.25 a = 26.0622

Notice that, this time, each local variable keeps its newly changed value when the function exits. Since a functions argument can receive different values as the function is called different times, we can test our program by passing different values to its argument as follows:
#include <iostream> using namespace std; void Starter(int y) { static double a = 112.50; static double b = 175.25; a = a / y; b = b + 2; cout cout cout cout } << << << << "y "a "b "b = = = / " " " a << y << endl; << a << endl; << b << endl; = " << b / a << "\n\n";

int main() { Starter(2); Starter(5); Starter(14); Starter(25); return 0; }

The current version of the program would produce:


y a b b y a b b y a b b y a b b = = = / = = = / = = = / = = = / 2 56.25 177.25 a = 3.15111 5 11.25 179.25 a = 15.9333 14 0.803571 181.25 a = 225.556 25 0.0321429 183.25 a = 5701.11

Static Functions Like a variable, a function also can be declared and/or defined as static. Here is an example:
#ifdef __BORLANDC__ #pragma argsused #endif #include <iostream> // #include "Exercise.h" using namespace std; static int GetNumberOfPages() { int pages = 842; return pages; } int main( int argc, char * argv[] ) { cout << "This book contains " << GetNumberOfPages() << " pages"; return 0; }

Logical Comparisons Logical Operators Introduction A program is a series of instructions that ask the computer (actually the compiler) to check some situations and to act accordingly. To check such situations, the computer spends a great deal of its time performing comparisons between values. A comparison is a Boolean operation that produces a true or a false result, depending on the values on which the comparison is performed. A comparison is performed between two values of the same type; for example, you can compare two numbers, two characters, or the names of two cities. On the other hand, a comparison between two disparate values doesn't bear any meaning. For example, it is difficult to compare a telephone number and somebody's age, or a music category and the distance between two points. Like the binary arithmetic operations, the comparison operations are performed on two values. Unlike arithmetic operations where results are varied, a comparison produces only one of two results. The result can be a logical true or false. When a comparison is true, it has an integral value of 1 or positive; that is, a value greater than 0. If the comparison is not true, it is considered false and carries an integral value of 0. The C++ language is equipped with various operators used to perform any type of comparison between similar values. The values could be numeric, strings, or objects (operations on objects are customized in a process referred to as Operator Overloading). The Equality Operator == To compare two variables for equality, C++ uses the == operator. Its syntax is:
Value1 == Value2

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our syntax, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.

Most of the comparisons performed in C++ will be applied to conditional statements; but because a comparison operation produces an integral result, the result of the comparison can be displayed on the monitor screen using a cout extractor. Here is an example:
#include <iostream> using namespace std; int main() { int Value = 15; cout << "Comparison of Value == 32 produces " << (Value == 32) << "\n\n"; return 0; }

The result of a comparison can also be assigned to a variable. As done with the cout extractor, to store the result of a comparison, you should include the comparison operation between parentheses. Here is an example:
#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 == 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n"; cout << "Comparison of Value1 == 15 produces " << (Value1 == 15) << "\n\n"; return 0; }

This would produce:


Value 1 = 15 Value 2 = 0

Comparison of Value1 == 15 produces 1 Very important

The equality operator and the assignment operator are different. When writing StudentAge = 12, this means the constant value 12 is assigned to the variable StudentAge. The variable StudentAge can change anytime and can be assigned another value. The constant 12 can never change and is always 12. The variable StudentAge is usually on the left side of the assignment operator. A constant, such as 12, is always on the right side and can never be on the left side of the assignment operator. This means you can write StudentAge = 12 but never 12 = StudentAge because when writing StudentAge = 12, you are modifying the variable StudentAge from any previous value to 12. Attempting to write 12 = StudentAge means you want to modify the constant integer 12 and give it a new value which is StudentAge: you would receive an error.NumberOfStudents1 == NumberOfStudents2 means both variables exactly mean the same thing. Whether using the first or the second, the compiler considers each as meaning the other. The Logical Not Operator ! When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. C++ considers that a variable whose value is null is stern. To render a variable unavailable during the evolution of a program, apply the logical not operator which is !. Its syntax is:
!Value

There are two main ways you can use the logical not operator. As we will learn when studying conditional statements, the most classic way of using the logical not operator is to check the state of a variable. To nullify a variable, you can write the exclamation point to its left. When used like that, you can display its value using the cout extractor. You can even assign it to another variable. Here is an example:
#include <iostream> using namespace std; int main() { int Value1 = 250; int Value2 = 32; int Value3 = !Value1;

// Display the value of a variable cout << "Value1 = " << Value1 << "\n"; // Logical Not a variable and display its value cout << "!Value2 = " << !Value2 << "\n"; // Display the value of a variable that was logically "notted" cout << "Value3 = " << Value3 << "\n"; return 0; }

When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. If the logical value was true, which is 1, it would be changed to false, which is 0. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is illustrated in the following example:
#include <iostream> using namespace std; int main() { int Value1 = 482; int Value2 = !Value1; cout << " Value1 = " << Value1 << "\n"; cout << " Value2 = " << Value2 << "\n"; cout << "!Value2 = " << !Value2 << "\n\n"; return 0; }

The Inequality Operator != As opposed to Equality, C++ provides another operator used to compare two values for inequality. This operation uses a combination of equality and logical not operators. It combines the logical not ! and a simplified == to produce !=. Its syntax is:
Value1 != Value2

The != is a binary operator (like all logical operator except the logical not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 != Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.

Here is an example:
#include <iostream> using namespace std; int main() { int Value1 = 212; int Value2 = -46; int Value3 = (Value1 != Value2); cout << "Value1 = " << Value1 << "\n"; cout << "Value2 = " << Value2 << "\n"; cout << "Value3 = " << Value3 << "\n\n"; return 0; }

The inequality is obviously the opposite of the equality. The Comparison for a Lower Value < To find out whether one value is lower than another, use the < operator. Its syntax is:
Value1 < Value2

The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.

Here is an example:
#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 < 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n\n"; return 0; }

Combining Equality and Lower Value <= The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its syntax is:
Value1 <= Value2

The <= operation performs a comparison as any of the last two. If both Value1 and Value2 hold the same value, the result is true or positive. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Here is an example:
#include <iostream> using namespace std; int main() { int Value1 = 15; int Value2 = (Value1 <= 24); cout << "Value 1 = " << Value1 << "\n"; cout << "Value 2 = " << Value2 << "\n\n"; return 0; }

The Comparison for a Greater Value > When two values of the same type are distinct, one of them is usually higher than the other. C++ provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its syntax is:
Value1 > Value2

Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value . Otherwise, the comparison renders false or null.

The Greater Than or Equal Operator >= The greater than and the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its syntax is:
Value1 >= Value2

A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result.

Here is a summary table of the logical operators we have studied: Operator Meaning == Equality to != Not equal to < Less than <= Less than or equal to > Greater than Greater than or equal >= to Accessories for Logical Conditions Boolean Variables The Boolean data type is used to declare a variable whose value would be set as true (1) or false (0). To declare such a value, you use the bool keyword. The variable can then be initialized with a starting Example a == b 12 != 7 25 < 84 Cab <= Tab 248 > 55 Val1 >= Val2 Opposite != == >= > <= <

value. The Boolean constant is used to check that the state of a variable (or a function) is true or false. You can declare such a variable as:
bool GotThePassingGrade = true;

Later in the program, for a student who got a failing grade, you can assign the other value, like this
GotThePassingGrade = false;

Here is an example:
#include <iostream> using namespace std; int main() { bool MachineIsWorking = true; cout << "Since this machine is working, its value is " << MachineIsWorking << endl; MachineIsWorking = false; cout << "The machine has stopped operating. " << "Now its value is " << MachineIsWorking << endl; return 0; }

Enumerations An enumeration provides a technique of setting a list of integers where each item of the list is ranked and has a specific name. For example, instead of numbers that represent players of a football (soccer) game such as 1, 2, 3, 4, 5, you can use names instead. This would produce GoalKeeper, RightDefender, LeftDefender, Stopper, Libero. The syntax of creating an enumeration is
enum Series_Name {Item1, Item2, Item_n};

In our example, the list of players by their name or position would be


enum Players { GoalKeeper, RightDefender, LeftDefender, Stopper, Libero };

Each name in this list represents a constant number. Since the enumeration list is created in the beginning of the program, or at least before using any of the values in the list, each item in the list is assigned a constant number. The items are counted starting at 0, then 1, etc. By default, the first item in the list is assigned the number 0, the second is 1, etc. Just like in a game, you do not have to follow a strict set of numbers. Just like a goalkeeper could have number 2 and a midfielder number 22, you can assign the numbers you want to each item, or you can ask the list to start at a specific number. In our list above, the goalkeeper would have No. 0. To make the list start at a specific number, assign the starting value to the first item in the list. Here is an example:
enum Players { GoalKeeper = 12, RightDefender, LeftDefender, Stopper, Libero };

This time, the goalkeeper would be No. 12, the RightDefender would be No. 13, etc. You still can assign any value of your choice to any item in the list, or you can set different ranges of values to various items. You can create a list like this:
enum Days { Mon, Tue, Wed, Thu, Fri, Sat, Sun = 0 };

Since Sun is No. 0, Sat would be No. 1, Fri would be 2 and so on. On the other hand, you can set values to your liking. Here is an example:
enum Colors { Black = 2, Green = 4, Red = 3, Blue = 5, Gray, White = 0 };

In this case, the Gray color would be 6 because it follows Blue = 5. Once the list has been created, the name you give to the list, such as Players, becomes an identifier of its own, and its can be used to declare a variable. Therefore, a variable of the enumerated type would be declared as:
Series_Name Variable;

You can declare more than one variable of such a type. An example of the type of our list of players would be:
Players Defense, Midfield, Attack; Players HandBall, BasketBall, VolleyBall;

Instead of declaring variables after the list has been created, you can declare the variables of that type on the right side of the list but before the closing semi-colon. Here is an example of a color enumeration and variables declared of that type:
enum Flags {Yellow, Red, Blue, Black, Green, White} Title, Heading1, BottomLine; #include <iostream> using namespace std; main() { enum PizzaSize {psSmall, psMedium, psLarge, psJumbo}; cout cout cout cout } << << << << "The "The "The "The small pizza has a value of " << psSmall << endl; medium pizza has a value of " << psMedium << endl; large pizza has a value of " << psLarge << endl; jumbo pizza has a value of " << psJumbo << endl;

To assign your own values to the list, you could change the enumeration as follows:
enum PizzaSize {psSmall = 4, psMedium = 10, psLarge = 16, psJumbo = 24};

To get the starting as you want, change the enumeration as follows:

#include <iostream> using namespace std; main() { enum PizzaSize {psSmall = 4, psMedium, psLarge, psJumbo}; cout cout cout cout } << << << << "The "The "The "The small pizza has a value of " << psSmall << endl; medium pizza has a value of " << psMedium << endl; large pizza has a value of " << psLarge << endl; jumbo pizza has a value of " << psJumbo << endl;

This would produce:


The The The The small pizza has a value of 4 medium pizza has a value of 5 large pizza has a value of 6 jumbo pizza has a value of 7

Press any key to continue...

To assign values at random, you could change the list of pizzas as follows:
enum PizzaSize {psSmall = 2, psMedium, psLarge = 14, psJumbo = -5};

This would produce:


The The The The small pizza has a value of 2 medium pizza has a value of 3 large pizza has a value of 14 jumbo pizza has a value of -5

Press any key to continue...

Conditional Statements Conditions Overview of Conditions When programming, you will ask the computer to check various kinds of situations and to act accordingly. The computer performs various comparisons of various kinds of statements. These statements come either from you or from the computer itself, while it is processing internal assignments. Lets imagine you are writing an employment application and one question would be, "Do you consider yourself a hot-tempered individual?" The source file of such a program would look like this:
#include <iostream> using namespace std;

int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual? "; cin >> Answer; return 0; }

Some of the answers a user would type are y, yes, Y, Yes, YES, n, N, no, No, NO, I dont know, Sometimes, Why are you asking?, and What do you mean? The variety of these different answers means that you should pay attention to how you structure your programs, you should be clear to the users.

A better version of the line that asks the question would be: cout << "Do you consider yourself a hot-tempered individual? (y=Yes/n=No)"; This time, although the user can still type anything, at least you have specified the expected answers. Introduction to Conditional Statements There are three entities that participate on a traffic light: the lights, the human beings who interact with the light, and the law. The road provides a platform on which these components come together. The Traffic Light Everything taken into consideration, a traffic light is made of three light colors: Green Yellow/Orange Red. When the light is green, the road is clear for moving in. The red light signals to stop and wait. A yellow light means, Be careful, it is not safe to proceed right now. Maybe you should wait. When it is not blinking, the yellow light usually serves as a transition period from green to red. There is no

transition from red to green. The Drivers There are two main categories of people who deal with the traffic light: the drivers and the walkers. To make our discussion a little simpler, we will consider only the driver. When the light is green, a driver can drive through. When the light is red, the driver is required to stop and wait. The Law Rules and regulations dictate that when a driver does not obey the law by stopping to a red light, he is considered to have broken the law and there is a consequence. The most independent of the three entities is the traffic light. It does not think, therefore it does not make mistakes. It is programmed with a timer or counter that directs it when to act, that is, when to change lights. The second entity, the driver, is a human being who can think and make decisions based on circumstances that are beyond human understanding. A driver can decide to stop at a green light or drive through a red light A driver who proceeds through a red light can get a ticket depending on one of two circumstances: either a police officer caught him hand-in-the-basket or a special camera took a picture. Worse, if an accident happens, this becomes another story. The traffic light is sometimes equipped with a timer or counter. We will call it Timer T. It is equipped with three lights: Green, Yellow, and Red. Lets suppose that the light stays green for 45 seconds, then its turns and stays yellow for 5 seconds, and finally it turns and stays red for 1 minute = 60 seconds. At one moment in the day, the timer is set at the beginning or is reset and the light is green: T = 0. Since the timer is working fine, it starts counting the seconds 1, 2, 3, 4, 45. The light will stay green from T = 0 to T = 45. When the timer reaches 45, the timer is reset to 0 and starts counting from 0 until it reaches 5; meanwhile, Color = Yellow. if a Condition is True In C++, comparisons are made from a statement. Examples of statements are:

"You are 12 years old" "It is raining outside" You live in Sydney"

When a driver comes to a traffic light, the first thing he does is to examine the light's color. There are two values the driver would put together: The current light of the traffic and the desired light of the traffic. Upon coming to the traffic light, the driver would have to compare the traffic light variable with a color he desires the traffic light to have, namely the green light (because if the light is green, then the driver can drive through). The comparison is performed by the driver making a statement such as "The light is green".

After making a statement, the driver evaluates it and compares it to what must be true. When a driver comes to a traffic light, he would likely expect the light to be green. Therefore, if the light is green (because that is what he is expecting), the result of his examination would receive the Boolean value of TRUE. This produces the following table:
Color Statement Boolean Value

The light is green

true

One of the comparisons the computer performs is to find out if a statement is true (in reality, programmers (like you) write these statements and the computer only follows your logic). If a statement is true, the computer acts on a subsequent instruction. The comparison using the if statement is used to check whether a condition is true or false. The syntax to use it is: if(Condition) Statement; If the Condition is true, then the compiler would execute the Statement. The compiler ignores anything else:

If the statement to execute is (very) short, you can write it on the same line with the condition that is being checked. Consider a program that is asking a user to answer Yes or No to a question such as "Are you ready to provide your credit card number?". A source file of such a program could look like this:
#include <iostream> using namespace std; int main() { char Answer;

// Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer; // Since the user is ready, let's process the credit card transaction if(Answer == '1') cout << "\nNow we will get your credit card information.\n"; cout << "\n"; return 0; }

You can write the if condition and the statement on different lines; this makes your program easier to read. The above code could be written as follows:
#include <iostream> using namespace std; int main() { char Answer; // Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer; // Since the user is ready, let's process the credit card transaction if(Answer == '1') cout << "\nNow we will get your credit card information.\n"; cout << "\n"; return 0; }

You can also write the statement on its own line if the statement is too long to fit on the same line with the condition. Although the (simple) if statement is used to check one condition, it can lead to executing multiple dependent statements. If that is the case, enclose the group of statements between an opening curly bracket { and a closing curly bracket }. Here is an example:
#include <iostream> using namespace std; int main() { char Answer; char CreditCardNumber[40]; // Request the availability of a credit card from the user cout << "Are you ready to provide your credit card number(1=Yes/0=No)? "; cin >> Answer;

// Since the user is ready, let's process the credit card transaction if(Answer == '1') { cout << "\nNow we will continue processing the transaction."; cout << "\nPlease enter your credit card number without spaces: "; cin >> CreditCardNumber; } cout << "\n"; return 0; }

If you omit the brackets, only the statement that immediately follows the condition would be executed. When studying logical operators, we found out that if a comparison produces a true result, it in fact produces a non zero integral result. When a comparison leads to false, its result is equivalent to 0. You can use this property of logical operations and omit the comparison if or when you expect the result of the comparison to be true, that is, to bear a valid value. This is illustrated in the following program:
#include <iostream> using namespace std; int main() { int Number; cout << "Enter a non zero number: "; cin >> Number; if(Number) cout << "\nYou entered " << Number << endl; cout << endl; return 0; }

Using the Logical Not When a driver comes to a light that he expects to be green, we saw that he would use a statement such as, "The light is green". If in fact the light is green, we saw that the statement would lead to a true result. If the light is not green, the "The light is green" statement produces a false result. This is shown in the following table:
Color Statement Boolean Value

The light is green The light is green

true false

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:

Color

Statement

Boolean Value

The light is green The light is not green

true true

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:
Color Statement Boolean Value Symbol

The light is green The light is not green

true false

P !P

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:
Color Statement Boolean Value Integer Value

The light is green The light is not green

true false

1 0

Otherwise: ifelse The if condition is used to check one possibility and ignore anything else. Usually, other conditions should be considered. In this case, you can use more than one if statement. For example, on a program that asks a user to answer Yes or No, although the positive answer is the most expected, it is important to offer an alternate statement in case the user provides another answer. Here is an

example:
#include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // First Condition { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } if( Answer == 'n' ) // Second Condition cout << "\nYou are hired!\n"; return 0; }

The problem with the above program is that the second if is not an alternative to the first, it is just another condition that the program has to check and execute after executing the first. On that program, if the user provides y as the answer to the question, the compiler would execute the content of its statement and the compiler would execute the second if condition. You can also ask the compiler to check a condition; if that condition is true, the compiler will execute the intended statement. Otherwise, the compiler would execute alternate statement. This is performed using the syntax: if(Condition) Statement1; else Statement2;

The above program would better be written as:


#include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // One answer { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else // Any other answer cout << "\nYou are hired!\n"; return 0; }

The Ternary Operator (?:) The conditional operator behaves like a simple ifelse statement. Its syntax is: Condition ? Statement1 : Statement2; The compiler would first test the Condition. If the Condition is true, then it would execute Statement1, otherwise it would execute Statement2. When you request two numbers from the user and would like to compare them, the following program would do find out which one of both numbers is higher. The comparison is performed using the conditional operator:
#include <iostream> using namespace std; int main() { signed Num1, Num2, Max; cout << "Enter two numbers: "; cin >> Num1 >> Num2; Max = (Num1 < Num2) ? Num2 : Num1; cout << "\nThe maximum of " << Num1 << " and " << Num2 << " is " << Max; return 0; }

Conditional Statements: ifelse if and ifelse ifelse

The previous conditional formula is used to execute one of two alternatives. Sometimes, your program will need to check many more than that. The syntax for such a situation is: if(Condition1) Statement1; else if(Condition2) Statement2; An alternative syntax would add the last else as follows: if(Condition1) Statement1; else if(Condition2) Statement2; else Statement-n; if(Condition1) Statement1; else if(Condition2) Statement2; else if(Condition3) Statement3; else Statement-n;

The compiler will check the first condition. If Condition1 is true, it will execute Statement1. If Condition1 is false, then the compiler will check the second condition. If Condition2 is true, it will execute Statement2. When the compiler finds a Condition-n to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition. This means you can include as many conditions as you see fit using the else if statement. If after examining all the known possible conditions you still think that there might be an unexpected condition, you can use the optional single else. A program we previously wrote was considering that any answer other than y was negative. It would be more professional to consider a negative answer because the program anticipated one. Therefore, here is a better version of the program:
#include <iostream> using namespace std; int main() { char Answer; cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer; if( Answer == 'y' ) // Unique Condition { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else if( Answer == 'n' ) // Alternative cout << "\nYou are hired!\n"; else

cout << "\nThat's not a valid answer!\n"; return 0; }

The switch Statement When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: { to }. The syntax of the switch statement is: switch(Expression) { case Choice1: Statement1; case Choice2: Statement2; case Choice-n: Statement-n; } The expression to examine is an integer. Since an enumeration (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:
#include <iostream> using namespace std; int main() { int Number; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << "\nYou typed 1."; case 2: cout << "\nYou typed 2."; case 3: cout << "\nYou typed 3."; } return 0; }

The program above would request a number from the user. If the user types 1, it would execute the

first, the second, and the third cases. If she types 2, the program would execute the second and third cases. If she supplies 3, only the third case would be considered. If the user types any other number, no case would execute. When establishing the possible outcomes that the switch statement should consider, at times there will be other possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be: switch(Expression) { case Choice1: Statement1; case Choice2: Statement2; case Choice-n: Statement-n; default: Other-Possibility; } Therefore another version of the program above would be
#include <iostream> using namespace std; int main() { int Number; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << case 2: cout << case 3: cout << default: cout << } return 0; }

"\nYou typed 1."; "\nYou typed 2."; "\nYou typed 3."; endl << Number << " is out of the requested range.";

Counting and Looping

The C++ language provides a set of control statements that allows you to conditionally control data input and output. These controls are referred to as loops. The while Statement The while statement examines or evaluates a condition. The syntax of the while statement is: while(Condition) Statement;

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop. Here is an example:
int Number; while( Number <= 12 ) { cout << "Number " << Number << endl; Number++; }

To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use a get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

An example would be:


#include <iostream> using namespace std; int main() { int Number;// = 0; while( Number <= 12 ) { cout << "Number " << Number << endl; Number++; } return 0; }

The do...while Statement The dowhile statement uses the following syntax: do Statement while (Condition);

The dowhile condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop. If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole dowhile statement must end with a semicolon. Another version of the counting program seen previously would be:
#include <iostream> using namespace std; int main() { int Number = 0; do cout << "Number " << Number++ << endl; while( Number <= 12 ); return 0; }

If the Statement is long and should span more than one line, start it with an opening curly braket and end it with a closing curly bracket. The dowhile statement can be used to insist on getting a specific value from the user. For example, since our ergonomic program would like the user to sit down for the subsequent exercise, you can modify your program to continue only once she is sitting down. Here is an example on how you would accomplish that:
#include <iostream> using namespace std;

int main() { char SittingDown; cout << "For the next exercise, you need to be sitting down\n"; do { cout << "Are you sitting down now(y/n)? "; cin >> SittingDown; } while( !(SittingDown == 'y') ); cout << "\nWonderful!!!"; return 0; }

The for Statement The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is: for( Start; End; Frequency) Statement; The Start expression is a variable assigned the starting value. This could be Count = 0; The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting. The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count. Here is an example that applies the for statement:
#include <iostream> using namespace std; int main() { for(int Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; return 0; }

The C++ compiler recognizes that a variable declared as the counter of a for loop is available only in that for loop. This means the scope of the counting variable is confined only to the for loop. This allows different for loops to use the same counter variable. Here is an example:
#include <iostream> using namespace std; int main() { for(int Count = 0; Count <= 12; Count++)

cout << "Number " << Count << endl; cout << endl; for(int Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl; return 0; }

Some compilers do not allow the same counter variable in more than one for loop. The counter variables scope spans beyond the for loop. With such a compiler, you must use a different counter variable for each for loop. An alternative to using the same counter variable in different for loops is to declare the counter variable outside of the first for loop and call the variable in the needed for loops. Here is an example:
#include <iostream> using namespace std; int main() { int Count; for(Count = 0; Count <= 12; Count++) cout << "Number " << Count << endl; cout << endl; for(Count = 10; Count >= 2; Count--) cout << "Number " << Count << endl; return 0; }

Constructing Expressions Accessories for Conditional Statements Introduction There are techniques you can use to combine conditional statements when one of them cannot fully implement the desired behavior. We will continue with our traffic light analogy. Nesting Conditions A condition can be created inside of another to write a more effective statement. This is referred to as nesting conditions. Almost any condition can be part of another and multiple conditions can be included inside of others. As we have learned, different conditional statements are applied in specific circumstances. In some situations, they are interchangeable or one can be applied just like another, which becomes a matter of

choice. Statements can be combined to render a better result with each playing an appropriate role. 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 dowhile statement to wait for the user to sit down; but as the dowhile 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; if( SittingDown != 'y' ) cout << "\nCould you please sit down for the next exercise?\n"; } while( !(SittingDown == 'y') ); cout << "\nWonderful!!!\n"; return 0; }

Here is an example of running the program:


Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? n Could you please sit down for the next exercise? Are you sitting down now(y/n)? y Wonderful!!! Press any key to continue...

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; if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise..."; cout << "\n...\nEnd of exercise"; char WantToContinue; cout << "Do you want to continue(y=Yes/n=No)? "; cin >> 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)? "; cin >> SittingDown; if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; char WantToContinue; cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> 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"; cout << "\nWe will stop the session now\nThanks.\n"; 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; if( SittingDown != 'y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n\n"; }while( SittingDown != 'y' ); cout << "Wonderful. Now we will continue today's exercise...\n"; cout << "\n...\n\nEnd of exercise\n"; char WantToContinue; cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> 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"; cout << "\nWe will stop the session now\nThanks.\n"; return 0; }

Conditional Statements Accessories break The break statement is used to stop a loop for any reason or condition the programmer sees considers fit. The break statement can be used in a while condition to stop an ongoing action. The syntax of the break statement is simply: 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';

while( Letter <= 'n' ) { cout << "Letter " << Letter << endl; break; } return 0; }

The break statement can also be used in a dowhile or a for loop the same way. 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; cout << "Type a number between 1 and 3: "; cin >> Number; switch (Number) { case 1: cout << break; case 2: cout << break; case 3: cout << break; default: cout << range."; } return 0; }

"\nYou typed 1."; "\nYou typed 2."; "\nYou typed 3."; endl << Number << " is out of the requested

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; cout << "Type a letter: "; cin >> Letter; switch( Letter ) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': cout << "The letter you typed, " << Letter << ", is a vowel\n"; break; case 'b':case 'c':case 'd':case 'f':case 'g':case 'h':case 'j': case 'k':case 'l':case 'm':case 'n':case 'p':case 'q':case 'r': case 's':case 't':case 'v':case 'w':case 'x':case 'y':case 'z': cout << Letter << " is a lowercase consonant\n"; break; case 'B':case 'C':case 'D':case 'F':case 'G':case 'H':case 'J': case 'K':case 'L':case 'M':case 'N':case 'P':case 'Q':case 'R': case 'S':case 'T':case 'V':case 'W':case 'X':case 'Y':case 'Z': cout << Letter << " is a consonant in uppercase\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; enum TEmploymentStatus { esFullTime, esPartTime, esContractor, esNS }; int main() {

int EmplStatus; cout << "Employee's Contract Status: "; cout << "\n0 - Full Time | 1 - Part Time" << "\n2 - Contractor | 3 - Other" << "\nStatus: "; cin >> EmplStatus; cout << endl; switch( EmplStatus ) { case esFullTime: cout << "Employment Status: Full Time\n"; cout << "Employee's Benefits: Medical Insurance\n" << " Sick Leave\n" << " Maternal Leave\n" << " Vacation Time\n" << " 401K\n"; break; 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; }

continue The continue statement uses the following syntax: continue; When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, dowhile 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; // Request 4 positive numbers from the user cout << "Type 4 positive numbers.\n"; // Make sure the user types 4 positive numbers for( int Count = 1; Count <= 4; Count++ ) { cout << "Number: "; cin >> posNumber; // If the number typed is not positive, ignore it if( posNumber < 0 ) continue; // Add each number to the sum Sum += posNumber; } // Display the sum cout << "\nSum of the numbers you entered = " << Sum << "\n\n"; return 0; }

goto The goto statement allows a program execution to jump to another section of the function in which it is being used. 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() { for(int Count = 0; Count <= 12; ++Count) {

cout << "Count " << Count << endl; if( Count == 5 ) goto MamaMia; } MamaMia: cout << "Stopped at 5"; return 0; }

Logical Operations on Statements The conditional Statements we have used so far were applied to single situations. You can combine statements using techniques of logical thinking to create more complex and complete expressions. One way to do this is by making sure that two conditions are met for the whole expression to be true. On the other hand, one or the other of two conditions can produce a true condition, as long as one of them is true. This is done with logical conjunction or disjunction. Using the Logical Not When a driver comes to a light that he expects to be green, we saw that he would use a statement such as, "The light is green". If in fact the light is green, we saw that the statement would lead to a true result. If the light is not green, the "The light is green" statement produces a false result. This is shown in the following table:
Color Statement Boolean Value

The light is green The light is green

true false

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:

Color

Statement

Boolean Value

The light is green The light is not green

true true

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:
Color Statement Boolean Value Symbol

The light is green The light is not green

true false

P !P

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:
Color Statement Boolean Value Integer Value

The light is green The light is not green

true false

1 0

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; cout << "Specify your position:\n" << "1 - Sitting Down\n" << "2 - Standing Up\n" << "3 - Laying Down\n"; cin >> 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 users 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; cout << "Are you sitting down (1=Yes/0=No)? "; cin >> SittingDown; if( SittingDown == 1 ) cout << "\nGood, now we will continue our next assignment.\n"; 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 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; cout << "Are you sitting down (1=Yes/0=No)? "; cin >> SittingDown; if( !(SittingDown == 1) ) cout << "\nCould you please sit down for the next exercise?\n"; cout << "\nWonderful!!!\n\n"; return 0; }

Logical Conjunction: AND The law of the traffic light states that if a driver drives through a red light, he or she has broken the law. Three things happen here: 1. The traffic light is red 2. The driver is driving 3. The law is broken Lets segment these expressions and give each a name. The first statement will be called L. Therefore, L <=> The traffic light is red The second statement will be called D. This means D <=> The driver is driving through the light The last statement will be called B, which means B <=> The law is broken 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 true D true B 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 displays 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. Combining 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:
L true D true L && D true B TRUE

When the traffic light is not red, regardless of the lights 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 false D true L && D false B 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 true D false L && D false B 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 false D false L && D false B FALSE

From our tables, the law is broken only when the light is red AND a driver drives through it. This produces:
L true false true false D true true false false L && D true false false false B TRUE 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 items size. Such a program could be written (or started) as follows:
#include <iostream> using namespace std; int main() { int PizzaSize; cout << "Select your pizza size"; cout << "\n1=Small | 2=Medium"; cout << "\n3=Large | 4=Jumbo"; cout << "\nYour Choice: "; cin >> PizzaSize; if(PizzaSize >= 0 && PizzaSize <= 4) cout << "Good Choice. Now we will proceed with the toppings\n"; else cout << "Invalid Choice\n"; 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; if( SittingDown != 'y' && SittingDown != 'Y' ) cout << "Could you please sit down for the next exercise?"; cout << "\n"; } while( SittingDown != 'y' && SittingDown != 'Y' ); cout << "Wonderful!!!";

return 0; }

Logical Disjunction: OR Lets assume that a driver has broken the law by driving through a red traffic light but there was no accident (to make our discussion simpler). There are two ways he can get a ticket: a police officer saw him, a special camera took a picture. This time again, we have three statements to make: S <=> A police officer saw the driver H <=> A camera took a picture of the action T <=> The driver got a ticket 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. If the driver gets a ticket, the The driver gets a ticket statement is true, which means T is true.
S true H true T 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. Lets 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 true H Don't Care T 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 Don't Care H true T 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 true H true T 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 true false true false H true true false false S || H true true true false T TRUE TRUE TRUE 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 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; if( Answer == 'y' || Answer == 'Y' ) // Unique Condition { cout << "\nThis job involves a high level of selfcontrol."; cout << "\nWe will get back to you.\n"; } else if( Answer == 'n' || Answer == 'N' ) // Alternative cout << "\nYou are hired!\n"; else cout << "\nThat was not a valid answer!\n"; return 0; }

Conditional Statements and functions

Using Conditions in Functions The use of functions in a program allows you to isolate assignments and confine them to appropriate entities. While the functions take care of specific requests, you should provide them with conditional statements to validate what these functions are supposed to do. There are no set rules to the techniques involved; everything depends on the tasks at hand. Once again, you will have to choose the right tools for the right job. To make effective use of functions, you should be very familiar with different data types because you will need to return the right value. 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; if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n"; } while( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ); 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; }

Functions do not have to return a value in order to be involved with conditional statements. In fact, both issues are fairly independent. This means, void and non-void functions can manipulate values

based on conditions internal to the functions. This is illustrated in the following program that is an enhancement to an earlier ergonomic program:
#include <iostream> using namespace std; #define Or || #define And && char GetPosition() { char Position; do { cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n"; } while( Position != 'y' Position != Position != 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..."; And 'Y' And 'n' And 'N' );

} int main() { char Position, WantToContinue; Position = GetPosition(); if( Position cout exercise?"; else { cout exercise...\n"; cout } == 'n' Or Position == 'N' ) << "\nCould you please sit down for the next

<< "\nWonderful!\nNow we will continue today's << "\n...\n\nEnd of exercise\n";

cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> WantToContinue; if( WantToContinue == '1' ) 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"; } cout << "\nWe will stop the session now\nThanks.\n"; return 0; }

Conditional Returns A function defined other than void must always return a value. Sometimes, a function will perform some tasks whose results would lead to different consequences. A function can return only one value (this is true for this context, but we know that there are ways to pass arguments so that a function can return more than one value) but you can make it render a result depending on a particular behavior. Image that a function is requesting an answer from the user. Since the user can provide different answers, you can treat each result differently. In the previous section, we saw an example of returning a value from a function. Following our employment application, here is an example of a program that performs a conditional return:
#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; if( Ans == 'y' ) return true; else return false; } int main() { bool Answer; Answer = GetAnswer(); if( Answer == true ) { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you.\n"; } else cout << "\nYou are hired!\n"; return 0; }

Imagine you write the following function:


#include <iostream> using namespace std; #define Or || #define And && string GetPosition() { char Position; cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position == 'y' Or Position == 'Y' ) return "Yes"; else if( Position == 'n' Or Position == 'N' ) return "No"; } 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 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 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:
#include <iostream> using namespace std; #define Or || #define And && string GetPosition() { char Position; cout << "Are you sitting down now(y/n)? "; cin >> Position; if( Position == 'y' Or Position == 'Y' ) return "Yes"; else if( Position == 'n' Or Position == 'N' ) return "No"; return "Invalid Answer"; } int main() { string Answer; Answer = GetPosition(); cout << "\nAnswer = " << Answer; return 0; }

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; if( Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ) cout << "Invalid Answer\n"; } while(Position != 'y' And Position != 'Y' And Position != 'n' And Position != 'N' ); if( Position == 'y' Or Position == 'Y' ) return 'y'; else if( Position == 'n' Or Position == 'N' ) return 'n'; // If you reach this point, none of the answers was valid 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..."; } bool ValidatePosition(char Pos) { if( Pos == 'y' Or Pos == 'Y' )

return true; else if( Pos == 'n' Or Pos == 'N' ) return false; // If you reached this point, we need to prevent a warning return false; } int main() { char Position, WantToContinue; bool SittingDown; Position = GetPosition(); SittingDown = ValidatePosition(Position); if( SittingDown cout << exercise?"; else { cout << exercise...\n"; cout << } == false ) "\nCould you please sit down for the next

"\nWonderful!\nNow we will continue today's "\n...\n\nEnd of exercise\n";

cout << "\nDo you want to continue(1=Yes/0=No)? "; cin >> WantToContinue; if( WantToContinue == '1' ) 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"; } cout << "\nWe will stop the session now\nThanks.\n"; return 0; }

Intermediate Operations

Bit Manipulations Introduction We learned in the previous lesson that, when you declare a variable, the compiler reserves an amount

of space in memory for that variable. Indeed, as we learned when studying bytes and words, a declared variable occupies space that resembles a group of small boxes. In our human understanding, it is not always easy to figure out how a letter such as as B is stored in 7 seven small boxes when we know that B is only one letter. Bit manipulation or a bit related operation allows you to control how values are stored in bits. This is not an operation you will need to perform very often, especially not in the early stages of your C++ journey. Nevertheless, bit operations (and related overloaded operators) are present on all GUI or application programming environments, so much that you should be aware of what they do or what they offer. At this time, you should (must) be aware of what a bit, byte, and a word are, as we saw in the previous lesson. Bits Operators: The Bitwise NOT Operator ~ One of the operations you can perform on a bit consists of reversing its value. That is, if a bit holds a value of 1, you may want to change it to 0 and vice-versa. This operation can be taken care of by the bitwise NOT operator that is represented with the tilde symbol ~ The bitwise NOT is a unary operator that must be placed on the left side of its operand as in
~Value

To perform this operation, the compiler considers each bit that is part of the operand and inverts the value of each bit from 1 to 0 or from 0 to 1 depending on the value the bit is holding. This operation can be resumed in the following table: Bit 1 0 ~Bit 0 1

Consider a number with a byte value such as 248. In our study of numeric systems, we define how to convert numbers from one system to another (this could be a good time to review or study the numeric systems). Based on this, the binary value of decimal 248 is 1111 1000 (and its hexadecimal value is 0xF8). If you apply the bitwise NOT operator on it to reverse the values of its bits, you would get the following result: Value ~Value 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1

Comparing Bits: The Bitwise AND Operator & The bitwise & is a binary operator that uses the following syntax
Operand1 & Operand2

This operator considers two values and compares the bit of each with the corresponding bit of the other value. If both corresponding bits are 1, the comparison produces 1. Otherwise, that is, if either bit is 0, the comparison produces 0. This comparison is resumed as follows: Bit1 Bit2 Bit1 & Bit2

0 1 0 1

0 0 1 1

0 0 0 1

Imagine you have two byte values represented as 187 and 242. Based on our study of numeric systems, the binary value of decimal 187 is 1011 1011 (and its hexadecimal value is 0xBB). The binary value of decimal 242 is 1111 0010 (and its hexadecimal value is 0xF2). Lets compare these two values bit by bit, using the bitwise AND operator: N1 N2 N1 & N2 1 1 1 0 1 0 1 1 1 Binary 1 1 1 0 1 0 0 0 0 1 1 1 1 0 0 Decimal 187 242 178

Most of the times, you will want the compiler to perform this operation and use the result in your program. This means that you can get the result of this operation and possibly display it on the console. The above operation can be performed by the following program:
#include <iostream> using namespace std; main() { const int N1 = 187; const int N2 = 242; cout << N1 << " & " << N2 << " = " << (N1 & N2) << "\n\n"; return 0; }

This would produce: 187 & 242 = 178 Comparing Bits: The Bitwise OR Operator | You can perform another type of comparison on bits using the bitwise OR operator that is represented by |. Its syntax is: Value1 | Value2 Once again, the compiler compares the corresponding bits of each operand. If at least one of the equivalent bits is 1, the comparison produces 1. The comparison produces 0 only if both bits are 0. This operation is resumed as follows: Bit1 0 1 0 1 Bit2 0 0 1 1 Bit1 | Bit2 0 1 1 1

Once again, lets consider decimals 187 and 242. Their bitwise OR comparison would render the following result: N1 N2 N1 | N2
#include <iostream> using namespace std; main() { const int N1 = 187; const int N2 = 242; cout << N1 << " | " << N2 << " = " << (N1 | N2) << "\n\n"; return 0; } This would produce: 187 | 242 = 251

1 1 1

0 1 1

1 1 1

Binary 1 1 1 0 1 1

0 0 0

1 1 1

1 0 1

Decimal 187 242 251

You can also let the compiler perform the operation and produce a result. Here is an example:

Comparing Bits: The Bitwise-Exclusive XOR Operator ^ Like the previous two operators, the bitwise-exclusive OR operator performs a bit comparison of two values. It syntax is:
Value1 ^ Value2

The compiler compares the bit of one value to the corresponding bit of the other value. If one of the bits is 0 and the other is 1, the comparison produces 1. In the other two cases, that is, if both bits have the same value, the comparison produces 0. This operation is resumed as follows: Bit1 0 1 0 1 Bit2 0 0 1 1 Bit1 ^ Bit2 0 1 1 0

We will again consider decimals 187 and 242. Their bitwise-exclusive XOR comparison would render the following result: Binary 1 1 1 0 0 1 Decimal 187 242 73

N1 N2 N1 ^ N2

1 1 0

0 1 1

1 1 0

0 0 0

1 1 0

1 0 1

If the compiler performs this operation, it can produce a result as in the following example:
#include <iostream> using namespace std; main() { const int N1 = 187; const int N2 = 242; cout << N1 << " ^ " << N2 << " = " << (N1 ^ N2) << "\n\n"; }

This would produce:


187 ^ 242 = 73

Bit Shift Operators: The Left Shift << In the previous lesson, we learned that bits are aligned in some consecutive manner to store data as needed. One operation you can perform on such bits consists of moving bits in a direction of your choice. C++ provides the left shift operator represented with << and its syntax is:
Value << ConstantInteger

The left shift operator, <<, is a binary operator whose right operand must be a constant integer. When performing the operation, the compiler would push Values bits to the left by the number of ConstantInteger. The number of ConstantInteger bits on the left side of Value would disappear. The bits on the left side of Value would replace them. After moving to the left, the space left by the most right bits would be filled with 0 bits. Imagine you have a variable named Value and whose value is 42. The binary value of 42 is 0010 1010 (you are probably asking, "Why the hell do I need to know this?" and my answer is, "I have no idea" but you ain't got no choice; ain't no one else gonna learn this stuff for you). Imagine you want to shift Value to the left by 2 bits. You would proceed as follows: 0 0 1 0 1 0 1 0 42 Shifted to the left by 2 bits << 2 0 0 1 0 1 0 1 0 0 0 7 6 5 The resulting binary number is 1010 1000 and its decimal value is 1*2 + 0*2 + 1*2 + 0*24 + 1*23 + 0*22 + 0*21 + 0*20 = 1*128 + 0*64 + 1*32 + 0*16 + 1*8 + 0*4 + 0*2 + 0*1 = 128 + 0 + 32 + 0 + 8 + 0 + 0 + 0 = 128 + 32 + 8 = 168 This can also be illustrated in the following program:
#include <iostream> using namespace std; main() { const int Value = 42;

cout << Value << " << 2 = " << (Value << 2) << "\n\n"; }

This would produce:


42 << 2 = 168

Bit Shift Operators: The Right Shift >> As opposed to the left operator, the right shift moves bits to the right by a natural number. Everything is done as for the left shift except that the concept is applied to the opposed direction. Therefore, if you shift 42 to the right, the binary result would be 0000 1010, whose decimal value is 10. Inline Assembly Introduction All the variables that we have used so far were declared in, and passed to, the random memory (RAM). Once a variable is declared and put in the memory, whenever it is involved in a calculation or assignment, the microprocessor sends a request to the memory to retrieve the value of the variable. The Central Processing Unit (CPU), also called the microprocessor, has its own memory. The microprocessor is made of memory cells called registers. Unlike the memory in the RAM, the access of the memory in the microprocessor is more precise; so precise that the registers are referred to by using their names. Some of the most commonly used registers (also called general purpose registers) are called EAX, EBX, ECX, EDX, ESI, etc. These registers are mostly used in the Assembly Language for low-level programming. Most modern compilers allow you to include Assembly Language code in your program. Using this feature, you can write a section or sections of Assembly language. When Assembly is included in your C++ program, it is referred to as Inline Assembly. Passing Values to Registers Using registers allows the programmer to write assignments directly destined for the microprocessor. The assignments and operations in the Assembly language are called instructions. When instructions are used by registers, the processing of the program is fast because the microprocessor does not have to retrieve the values of the variables in the RAM; these values, since existing in the registers, are readily available. A section that has Assembly code starts with __asm followed by some other techniques. When the compiler encounters this keyword, it knows that the subsequent code would be in Assembly language and it would treat it accordingly. For example, instead of performing a calculation in the RAM, the following program will assign values to two integer variables, namely Number1 and Number2, then it calculate their sum of those two numbers and stores the result in another variable called Result. After the calculation, the Assembly section sends the result back to the C++ compiler to display the variables and their values:
#ifdef __BORLANDC__

#pragma argsused #endif

#include <iostream> using namespace std;

int main( int argc, char * argv[] ) { int Number1, Number2, Result;

__asm { MOV Number1, 248 // Initialize Number1 MOV Number2, 405 // Initialize Number2 MOV EAX, Number1 // Put the value of Number1 in the EAX register ADD EAX, Number2 // Add the value of Number2 to the content of EAX MOV Result, EAX } // Put the content of EAX into Result // That's it

cout << "Number1 = " << Number1 << endl; cout << "Number2 = " << Number2 << endl; cout << "\nAfter adding Number1 to Number2," << endl; cout << "Result = " << Result << endl;

return 0; }

This would produce:

umber1 = 248 Number2 = 405

After adding Number1 to Number2, Result = 653

Introduction to Arrays

Arrays Fundamentals Introduction

An array of airplanes

An array of bugs

An array of cards

An array of characters

When you look at the stuff on each group above, you realize that the items on each picture share a lot of characteristics, though each one still maintains specific features that set it apart from the others. Everyone of the items on the first picture is an airplane; if you decide to be specific, then you may state that the first airplane of the group is bright green while the second is black; the first and the fourth airplanes don't have helices although all the others do. On the second picture (from left to right), all of these items are bugs; they don't seem to look alike, but everyone of them is still a bug. If you play cards sometimes (Solitaire or FreeCell), then you are familiar with the third picture. Everyone of the items on the third picture is a card, same size, same white background, though they display different card values, different character colors (and they would have different effects depending on how your game is going). Whenever you are typing, you are aligning arrays of characters, characters as those of the last picture. This shows that a word or a sentence is actually a group or letters. An array is a group of items that can be identified as similar because they are of the same nature.

Arrays come in two flavors: one dimensional and multi-dimensional arrays. Everyone of the pictures above represents a single dimensional array. Declaring an Array Just like any variable you are already familiar with, an array has to be declared before being used. Yet the difference this time is that you need to tell the compiler what kind of array you are defining, an array of books? An array of students? An array of billiard balls? An arrays of clothes? This is because, once more, the compiler wants to know how much space your array is going to occupy in the computer memory. This is because when you declare an array of items, the compiler puts each one of the items in an appropriate location. Like any other variable, the syntax of declaring an array is:
DataType ArrayName[dimension\order]

The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its name that follows the C++ naming rules. The name is then followed by square brackets that specify the dimension of the array or its size. Here are examples of declaring arrays:
int age[12]; float grade[100]; double angle[360];

int Age[12]; declares a group or array of 12 values, each one being an integer. float Grade[100]; declares an array of 100 floating-point values. double Angle[360]; declares an array of double-precision numbers. There are 360 of these items in the group. Initializing an Array Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a onedimensional array, the syntax used is:
DataType ArrayName[dimension] = { element1, element2, , elementn};

Therefore, you can start with the data type to specify the kind of array you are declaring. This is followed by the array name, and the square brackets. After specifying the dimension or not, and after the closing square bracket, type the assignment operator. The elements, also called items, that compose the array are included between an opening curly bracket '{' and a closing curly bracket '}'. Each item is separate from the next by a comma operator. As a normal C/C++ initialization, you end it with a semicolon. Here are examples of declaring an initializing arrays:

int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12}; double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};

If you have decided to initialize the array while you are declaring it, you can omit the dimension. Therefore, these arrays can be declared as follows:
int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12}; double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

Processing the Elements of an Array After initializing an array, its elements are counted from left to right. Each element of the array, also called a member of the array, has a specific and constant position. The position of an item is also called its index. The first member of the array, the most left, has an index of 0. The second member of the array has an index of 1. Since each array has a number of items which can be specified as n, the last member of the array has an index of n-1 Based on this system of indexing, to locate a member of an array, use its index in the group. Imagine you declare and initialize an array as follows:
double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28};

To locate the value of the 3rd member of the array, you would type distance[2]. In the same way, the 1st member of the array can be located with distance[0]. Once you can locate a member of the array, you can display its value using cout. Here is an example:
#include <iostream> using namespace std; int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "2nd member = " << distance[1] << endl; cout << "5th member = " << distance[4] << endl; return 0; }

This would produce:


2nd member = 720.52 5th member = 6.28

Using this approach, each member of the array can have its value accessed. Here is an example:
#include <iostream> using namespace std; int main()

{ double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: 44.14 720.52 96.08 468.78 6.28

The Size of an Array When declaring an array, we saw that you must specify the number of items that the array is made of. Here is an example:
float averagePrice[45];

Depending on how you want to deal with your array, you may sometimes need to increase or decrease its dimension. To do this, you would need to locate the declaration of the array and change its dimension. If the program is long and the array is declared in some unusual place, this could take some time. The alternative is to define a constant prior to declaring the array and use that constant to hold the dimension of the array. Here is an example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

You can use such a constant in a for loop to scan the array and access each of its members. Here is an example:

#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Members of the array\n"; for(int i = 0; i < numberOfItems; ++i) cout << "Distance " << i + 1 << ": " << distance[i] << endl; return 0; }

In both cases, this would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28

We knew the dimensions of the arrays we have used so far, because we could count the number of members of the array. Imagine you declare a large array, possibly made of 100 or 300 members, you wouldn't start counting the number of members. C/C++ provides the sizeof operator that can be used to get the dimension of an array. The syntax you would use is:
sizeof(ArrayName) / sizeof(DataType)

Imagine you declare an array as follows:


int number[] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26, 12, 127, 4762, 823, 236, 84, 5};

Instead of counting the number of members of this array (it makes me dizzy when I try), you can use the sizeof operator as follows:
int NumberOfItemsOfTheArray = sizeof(Number)/sizeof(int);

One of the advantages of the sizeof operator used to get the number of members of the array is that it can be used on a for loop to scan an array, either to locate the members or to look for a value in the array. Here is an example of using this concept:
#include <iostream> using namespace std; int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28}; // Using the sizeof operator to get the dimension of the array int index = sizeof(distance) / sizeof(double);

cout << "Array members and their values\n"; // Using a for loop to scan an array for(int i = 0; i < index; ++i) cout << "Distance : " << i + 1 << distance[i] << endl; return 0; }

This would produce:


Array members and their values Distance : 144.14 Distance : 2720.52 Distance : 396.08 Distance : 4468.78 Distance : 56.28

Filling Up an Array When you declare an array without initializing it, we have mentioned that the compiler reserves an amount of memory space for the members of the array. But that is only what the compiler does. Each part of such reserved space is filled with garbage. Therefore, you must make sure that you know the value held by a member of the array before making any attempt to process the value held by that member of the array. Consider the following example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems]; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061 -9.25596e+061

As you can see, the members of the array in the beginning don't have any recognizable value. There are two solutions to this problem. You can either initialize the array or request the values of the members of the array from the user. So far, when we used an array, we made sure to provide the exact number of members we needed for the array. We also saw that we could declare and initialize an array without specifying its dimension.

The advantage of not specifying the dimension of the array is that we trust the compiler to find out the number of elements of the array. If you decide to specify the dimension of the array and initialize it, make sure you specify the elements less than or equal to the number you specified. Here is an example:
#include <iostream> using namespace std; int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08}; cout cout cout cout cout } << << << << << "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: " " " " " << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] << << << << << endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance Distance Distance Distance Distance 1: 2: 3: 4: 5: 44.14 720.52 96.08 0 0

If you provide more members than the number of elements you specified, the compiler would provide garbage values to the extra members. Here is an example:
#include <iostream> using namespace std; int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout cout cout cout cout cout cout cout } << << << << << << << << "Distance "Distance "Distance "Distance "Distance "Distance "Distance "Distance 1: 2: 3: 4: 5: 6: 7: 8: " " " " " " " " << << << << << << << << distance[0] distance[1] distance[2] distance[3] distance[4] distance[5] distance[6] distance[7] << << << << << << << << endl; endl; endl; endl; endl; endl; endl; endl;

return 0;

This would produce:


Distance 1: 44.14

Distance Distance Distance Distance Distance Distance Distance

2: 3: 4: 5: 6: 7: 8:

720.52 96.08 468.78 6.28 2.64214e-308 2.12414e-314 1.00532e-307

Depending on the compiler you are using, you would also receive a (strong) warning.

Streaming Array Members We have already seen how to define an array, how to locate the elements of an array, and how to display the values of these elements (displaying the value of a member of an array is one aspect of streaming). The arrays we have seen so far had their dimensions and their elements defined by the programmer. Many times you will have to get these elements from the user. When you need to get an array from the user, first decide on what kind of array it is. Next, try to think of the maximum number of members you will need for the array. When you define an array and specify its dimension, the compiler will reserve the number of cells in memory that can accommodate your array. Here is an example:
int Page[5];

Each member of the array can be located using its index, as we have seen so far. In the same way, you can request the value of any member of the array using its index. In the following example, we declare an array of 5 integers and then we request the values of the 1st and the 4th members:
#include <iostream> using namespace std; int main() { const int counter = 5; int page[counter]; cout << "Enter the number of pages of your books\n"; cout << "Book 1: "; cin >> page[0]; cout << "Book 4: "; cin >> page[3]; cout << "\nSummary of books"; cout << "\nBook 1: " << page[0] << " pages"; cout << "\nBook 4: " << page[3] << " pages\n"; return 0; }

Here is an example of running the program:


Enter the number of pages of your books

Book 1: 842 Book 4: 1204 Summary of books Book 1: 842 pages Book 4: 1204 pages

Operations on Arrays Each member of an array is a pseudo-variable and can be processed as such. This means that you can add the values of two members of the array(Number[2]+Number[0]), you can subtract the value of one of the members from another member(member[1]-Number[4]). In the same way, you can perform multiplication, division, or remainder operations on members of an array. One of the regular operations performed on an array consists of adding the values of the members to produce a sum. Here is an example:
#include <iostream> using namespace std; int main() { // We know that we need a constant number of elements const int max = 10; int number[max]; // We will calculate their sum int sum = 0; cout << "Please type 10 integers.\n"; for( int i = 0; i < max; i++ ) { cout << "Number " << i + 1 << ": "; cin >> number[i]; sum += number[i]; } cout << "\n\nThe sum of these numbers is " << Sum << "\n\n"; return 0; }

This would produce: Please type 10 integers. Number 1: 120 Number 2: 42 Number 3: 75 Number 4: 38 Number 5: 904 Number 6: 6 Number 7: 26 Number 8: 55

Number 9: 92 Number 10: 20 The sum of these numbers is 1378 Another type of operation regularly performed on an array consists of looking for a value held by one of its members. For example, you can try to know if one of the members holds a particular value you are looking for. Here is an example:
#include <iostream> using namespace std; int main() { // Declare the members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int find; int i, m = 8; cout << "Enter a number to search: "; cin >> find; for (i = 0; (i < m) && (Numbers[i] != Find); ++i) continue; // Find whether the number typed is a member of the array if (i == m) cout << find << " is not in the list" << endl; else cout << find << " is the " << i + 1 << "th element in the list" << endl; return 0; }

This would produce: Enter a number to search: 44 44 is the 4th element in the list One of the most regular operations performed consists of comparing the values of different members to get the lowest value of the members. Here is an example:
// Example of finding the minimum member of an array #include <iostream> using namespace std; int main() { // The members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int minimum = numbers[0]; int a = 8; // Compare the members for (int i = 1; i < a; ++i) { if (numbers[i] < minimum)

minimum = numbers[i]; } // Announce the result cout << "The lowest member value of the array is " << minimum << "." << endl; return 0; }

This would produce:


The lowest member value of the array is 8.

You can use this same approach to get the maximum value of the members of an array. Here is an example:
// Example of finding the maximum member of an array #include <iostream> using namespace std; int main() { // The members of the array int numbers[] = {8, 25, 36, 44, 52, 60, 75, 89}; int maximum = numbers[0]; int a = 8; // Compare the members for (int i = 1; i < a; ++i) { if (numbers[i] > maximum) maximum = numbers[i]; } // Announce the result cout << "The highest member value of the array is " << maximum << "." << endl; return 0; }

Arrays and Functions An array can be passed to a function as argument. An array can also be returned by a function. To declare and define that a function takes an array as argument, declare the function as you would do for any regular function and, in its parentheses, specify that the argument is an array. Here is an example:
#include <iostream> using namespace std; void DisplayTheArray(double member[5]); int main() {

const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; return 0; } void DisplayTheArray(double member[5]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

You don't have to specify the dimension of the array. This means that you can leave the square brackets empty:
#include <iostream> using namespace std; void DisplayTheArray(double member[]); int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; return 0; } void DisplayTheArray(double member[]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

We have already seen that when you declare an array, the compiler reserves an amount of memory space for the members of the array. To locate these members, the compiler aligns them in a consecutive manner. For example (hypothetically), if a member is located at 1804 Lockwood drive, the next member would be located at 1805 Lockwood Drive. This allows the compiler not only to know where the members of a particular array are stored, but also in what block (like the block houses of a city) the array starts. This means that, when you ask the compiler to locate a member of an array, the compiler starts where the array starts and moves on subsequently until it finds the member you specified. If the compiler reaches the end of the block but doesn't find the member you specified, it stops, instead of looking for it all over the computer memory. Based on this, when you call a function that has an array as argument, the compiler only needs the name of the array to process it. Therefore, the above function can be called as follows:
#include <iostream> using namespace std; void DisplayTheArray(double member[]) {

for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; } int main() { const int numberOfItems = 5; double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Members of the array"; DisplayTheArray(distance); return 0; }

This would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28

The good scenario we have used so far is that we know the number of members of our array and we can directly use it in the function that is passed the argument. Imagine that we want the function to know how many members the array has and we want to let the function know while we are calling it, after all, in some circumstances, we will not always know how many members we want the function to process. This should easily be done as follows:
#include <iostream> using namespace std; void DisplayTheArray(double member[]) { for(int i = 0; i < 5; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; } int main() { const int NumberOfItems = 5; double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28}; cout << "Members of the array"; DisplayTheArray(distance[3]); return 0; }

Unfortunately, this program will not compile. Remember, we saw that the compiler wants only the name of the array, because the name by itself represents the whole array. distance[3] is a specific value of a member of the array, it is not a group of values. In other words, distance[3] is the same as 468.78. It is as if we want to pass 468.78 as the value to be treated and not as a subsequent group of

values, because that is what an array is. Therefore, the compiler complains that you are passing a value after you have specifically stated that the argument was a group of values and not a single value. When you declare and define a function that takes an array as argument, if you plan to process the array, for example, if you want the calling function to control the number of elements to be processed, you should/must pass another argument that will allow the function to know how many members of the array would be considered. Such a function can be declared as follows:
#include <iostream> using namespace std; void DisplayTheArray(double mbr[], int count); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Processing 5 members of the array cout << "Members of the array"; DisplayTheArray(distance, 5); // Processing all members of the array int sizeOfArray = sizeof(Distance)/sizeof(double); cout << "\nMembers of the array"; DisplayTheArray(distance, sizeOfArray); return 0; } void DisplayTheArray(double member[], int counter) { for(int i = 0; i < counter; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

This would produce:


Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Members of the array Distance 1: 44.14 Distance 2: 720.52 Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Distance 6: 68.04

Distance 7: 364.55 Distance 8: 6234.12

Using this same concept of passing accompanying arguments, you can control how the called function would process the array. For example, you can specify the starting and end point to the processing of the array. Here is an example:
#include <iostream> using namespace std; // This function process an array but starts and ends at specific positions void DisplayTheArray(double mbr[], int Start, int End); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; DisplayTheArray(distance, 2, 6); return 0; } void DisplayTheArray(double member[], int start, int ending) { for(int i = start; i < ending; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

This would produce:


Members of the array Distance 3: 96.08 Distance 4: 468.78 Distance 5: 6.28 Distance 6: 68.04

When declaring a function that takes an array argument, as we learned with other arguments, you don't have to provide a name to the argument. Simply typing the square brackets on the right side of the data type in the parentheses is enough. The name of the argument is only necessary when defining the function. Therefore, the above function can be declared as follows:
#include <iostream> using namespace std; // This function process an array but starts and ends at specific positions void DisplayTheArray(double[], int, int); int main() { double distance[] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan the array from the 3rd to the 7th member cout << "Members of the array";

DisplayTheArray(distance, 2, 6); return 0; } void DisplayTheArray(double member[], int Start, int Ending) { for(int i = Start; i < Ending; ++i) cout << "\nDistance " << i + 1 << ": " << member[i]; cout << endl; }

Two-Dimensional Arrays Introduction A 2-dimensional array is an array of arrays. In other words, it is an array where each member of the array is also an array. Consider the following table Country\Data United States Cameroon Guatemala Map Flag Area (sq km) 9,629,091 475,440 108,890 Population 272,639,608 15,456,092 12,335,580

Italy

301,230

56,735,130

Oman

212,460

2,446,645

Declaring and Initializing a 2-Dimensional Array This two-dimensional array is made of rows and columns . Each column represents one category of data that everyone of the rows shares with the other rows. As different as each map looks, it still remains a map; each country on the table is known for its map, its flag, its area, and its population, though remaining different from the others. To see another two-dimensional array, look at a calendar that displays a month with its week days. Like the above table, a 2-dimensional array is made rows and columns. To declare it, use double pair of a opening and closing square brackets. Here is an example:
int numberOfStudentsPerClass[12][50];

This declaration creates a first group of 12 elements; it could be an array of 12 classes. Each element of the array contains 50 elements. In other words, each of the 12 members of the group is an array of 50 items. Simply stated, this declarations creates 12 classes and each class contains 50 students.

Before using the members of an arrays, you should/must make sure you know the values that its members hold. As done with one-dimensional arrays, there are two ways you can solve this problem: you can initialize the array or you can get its values by another means. You can initialize an array the same way you would proceed the a one-dimensional array: simply provide a list of values in the curly brackets. A multidimensional array is represented as an algebraic matrix as MxN. This means that the array is made of M rows and N columns. For example, a 5x8 matrix is made of 5 rows and 8 columns. To know the actual number of members of a multidimensional array, you can multiply the number of rows by the number of columns. Therefore a 2x16 array contains 2*16=32 members. Based on this, when initializing a 2-dimensional array, make sure you provide a number of values that is less than or equal to the number of members. Here is an example:
double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12};

To locate a member of the array, this time, each must be identified by its double index. The first member is indexed at [0][0]. The second is at [0][1]. For a 2x4 array as this one, the 5th member is at [1][0]. You can use this same approach to display the values of the members of the array. Here is an example:
#include <iostream> using namespace std; int main() { // A 2-Dimensional array double distance[2][4] = {44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12}; // Scan cout << cout << cout << cout << cout << cout << cout << cout << cout << the array from the 3rd to "Members of the array"; "\nDistance [0][0]" << ": "\nDistance [0][1]" << ": "\nDistance [0][2]" << ": "\nDistance [0][3]" << ": "\nDistance [1][0]" << ": "\nDistance [1][1]" << ": "\nDistance [1][2]" << ": "\nDistance [1][3]" << ": the 7th member " " " " " " " " << << << << << << << << distance[0][0]; distance[0][1]; distance[0][2]; distance[0][3]; distance[1][0]; distance[1][1]; distance[1][2]; distance[1][3];

cout << endl; return 0; }

This would produce:


Members of the array Distance [0][0]: 44.14

Distance Distance Distance Distance Distance Distance Distance

[0][1]: [0][2]: [0][3]: [1][0]: [1][1]: [1][2]: [1][3]:

720.52 96.08 468.78 6.28 68.04 364.55 6234.12

To make the above array a little easier to read when initializing it, you can type the values of each row on its own line. For example, the above array can be initialized as follows:
double distance[2][4] = { 44.14, 720.52, 96.08, 468.78, 6.28, 68.04, 364.55, 6234.12 };

C++ also allows you to include each row in its own pair of curly brackets. You must separate each row from the next with a comma. Once again, this makes code easier to read. Here is an example:
double distance[2][4] = { { 44.14, 720.52, 96.08, 468.78 }, { 6.28, 68.04, 364.55, 6234.12 } };

Processing a 2-Dimensional Array To scan a 2-dimensional array, you should know how many columns the array contains. You can use two for loops to navigate the array. Here is an example:
#include <iostream> using namespace std; int main() { // A 2-Dimensional array double distance[][4] = { { 44.14, 720.52, 96.08, 468.78 }, { 6.28, 68.04, 364.55, 6234.12 } }; // Scan the array from the 3rd to the 7th member cout << "Members of the array"; for(int i = 0; i < 2; ++i) for(int j = 0; j < 4; ++j) cout << "\nDistance [" << i << "][" << j << "]: " << distance[i][j]; cout << endl; return 0; }

This would produce the same result as previously. Multidimensional Arrays Multi-dimensional arrays are characterized by more than one line of representation. Here are examples of a three-dimensional arrays

Introduction to Pointers Pointers Fundamentals Introduction When writing a program, you declare the necessary variables that you will need in order to accomplish your work. When declaring variables, you are simply asking the computer to reserve a set amount of space in its memory for a particular object you want to use. When you declare a variable, the computer reserves an amount of space for that variable, and uses the variable's name to refer to that memory space. This will allow you to store something, namely the value of that variable, in that space. Indeed, the computer refers to that space using an address. Therefore, everything you declare has an address, just like the address of your house. You can find out what address a particular variable is using. A Review of References and Functions Here are a few things you know already about writing a program: To use a variable, you declare it first to tell the compiler what kind of variable you are planning to use and what its name is . Once you declare a variable, the compiler reserves and assigns it a portion of space in memory and locates it there so that whenever you need that variable, you just call it and then use it. To use a function, you have to define it, tell the compiler what the function is supposed to do, and whether the function is supposed to give back a result or not, after it has performed its assignment. To see a variable's address, you can use the & operator followed by the name of the variable. For example, after declaring an integer as
int numberOfStudents;

you can find the address where the NumberOfStudents variable is located by using:
cout << &numberOfStudents;

This program would give you the address of the declared variable:
#include <iostream> using namespace std;

int main() { int value;

cout << "Value lives at " << &value;

cout << "\n\n"; return 0; }

After executing the program, you could get:


Value lives at: 0x0065FDF4

Using Pointers Why Use Pointers? Every time you declare a variable, the compiler puts it somewhere, which you can now refer to as an address. Once you know that address, you can use it. Like a reference, when you pass an argument to a function, the argument is passed using its address. This allows the calling function to dig into the address of the variable (the argument) and use the value directly. This transaction, like that of passing an argument by reference, allows the calling function to alter the real value of the argument. Using this ability, a pointer can allow you to return many values from a function; as opposed to a regular argument passing where the data, although changed inside of the calling function, will regain its previous value once the calling function is exited. Therefore, passing arguments as pointers allows a function to return many values, even if a function is declared as void. When you declare an array, you must specify the dimension of the array. That's already a problem: what if you don't know and don't want to know the dimension of the array? Pointers provide an ability

that regular arrays do not have. Since pointers have a different and better system of managing memory, a pointer can store an array of almost any size; this is tremendous when dealing with arrays of characters or a whole text. Using this feature, when declaring a pointer in replacement of an array, you do not have to worry about the size of the array, the compiler will take care of that. Again, this feature allows you to pass pointers to a function (just like arrays) and return a value that has been altered even if the function is declared as void. This is even more dynamic with multidimensional arrays.

Definition Pointers are not particularly useful when declared and used inside of one function. They show their capabilities when different functions (and/or objects) exchange data stored in those pointers. As you can see from the execution of the program above, the address of a variable is very difficult to read and interpret. Fortunately, we don't need to know that address and we don't need to know what it means or where the variable is located. C++ provides an alternative to this problem. Instead of referring to a variable's address directly, you are allowed to declare another variable, and then use that new variable to refer to the address of the variable you are interested in. A pointer is a variable that refers to another variable's address. Just like any variable in C++, you should declare and initialize a pointer variable before using it. To declare a pointer variable, use an identifier, followed by an asterisk (*), followed by the name of the pointer, and a semi-colon. Here is the formula:
DataType * PointerName;

The identifier should be one of those we have learned already. This means it could be an int, a char, a double, etc. The identifier should be the same type of identifier the pointer variable will point to. Therefore, if you are declaring a pointer that will point to an integer variable, the pointer identifier should be an integer. The asterisk (*) lets the compiler know that the variable that follows is a pointer. There are three ways you can type the asterisk. These are
DataType* PointerName; DataType * PointerName; DataType *pointerName;

By default, it does not matter how you append the *, the compiler will know that the thing that follows is a variable. Be careful when declaring various pointers. If you declare a few of them on the same line, like this:
DataType* pointer1, pointer2;

Only the first variable is a pointer, the second is a regular variable. If you want to declare different variables, you use:
DataType* pointer1, *pointer2;

Or
DataType* pointer1; DataType* pointer2;

Since the name of the pointer is indeed the name of a variable, you will follow the naming rules that govern every C++ variable.
#include <iostream> using namespace std;

int main() { int value; int *pointer;

cout << "Value lives at " << &value << "\n"; cout << "Pointer lives at " << &pointer;

cout << "\n\n"; return 0; }

After executing the program, you might get:


Value lives at: 0x0065FDF4 Pointer lives at: 0x0065FDF0

Initializing a Pointer One of the reasons you are using a pointer is to find an alternative to knowing the address of a variable.

Therefore, from now on, we are not interested in a variable's real address. Instead, we will use a pointer to point to that variable. As we have learned already, a variable should be initialized before being used. This allows the compiler to put something into the memory space allocated for that variable. To use a pointer P effectively, for its intended purpose, you need to tell the compiler that: pointer P will be used to point to the address of variable V. You do this by initializing the pointer. A pointer is initialized (almost) like any other variable, using the assignment operator (=). There are two main ways you can initialize a pointer. When declaring a pointer like this:
int* Pointer;

initialize it by following the assignment operator with & operator and the name of the variable, like this
int* Pointer = &Variable;

You can also initialize a pointer on a different line, after declaring it. This time, you should not use the asterisk on the Pointer, but the compiler should know that the pointer will point to a variable's address; therefore, the name of the variable will still use the &.
#include <iostream> using namespace std;

int main() { int value = 12; int *pointer = &value;

cout << "Value lives at: " << value << "\n"; cout << "Pointer lives at: " << *pointer; cout << "\n\n"; return 0; }

The program would produce:


Value lives at: 12

Pointer lives at: 12

This program could also have the pointer initialized as:


#include <iostream> using namespace std;

int main() { int Value = 12; int *pointer;

cout << "Value lives at: " << value << "\n";

Pointer = &value; cout << "Pointer lives at: " << *pointer; cout << "\n\n"; return 0; }

And it would produce the same result. As another of the program, you can first declare both variables, then initialize them later on, when needed:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

pointer = &value; Value = 26;

cout << "Value = " << value << "\n"; cout << "*Pointer = " << *pointer << "\n";

cout << "\n"; return 0; }

Once you have declare a variable and assign it to a pointer, during the course of your program, the value of a variable is likely to change, you can therefore assign it a different value:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

Pointer = &value; Value = 26; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

Value = 35; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

cout << "\n"; return 0; }

As you know now, both *pointer and Value have the same value. This allows you to change the value

of the pointer directly and affect the main variable meanwhile. Therefore, you can safely change the value of the pointer and it will be assigned accordingly. To see an example, make the following change to the file:
#include <iostream> using namespace std;

int main() { int value; int *pointer;

Pointer = &value; Value = 26; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

Value = 35; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

*pointer = 144; cout << "Value = " << value << "\n"; cout << "*pointer = " << *pointer << "\n";

cout << "\n"; return 0; }

This would produce:


Value = 26

*pointer = 26 Value = 35 *pointer = 35 Value = 144 *pointer = 144

A Pointer to a Pointer Instead of pointing to a regular variable, a pointer can be made to point to another pointer. To apply this, always remember that you must specify what target a pointer is pointing to. Once again, consider the following example:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer;

pointer = &value;

cout << " Value

= " << value << "\n";

cout << "*Pointer = " << *pointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26

In this program, if necessary, you can declare a new variable that is a pointer that itself points to

another pointer. When declaring such a variable, precede it with two *. After declaring the pointer, before using it, you must initialize it with a reference to a pointer, that is, a reference to a variable that was declared as a pointer. Here is an example:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

pointer = &value; pointerToPointer = &pointer;

cout << " cout << "

Value

= " << value << "\n";

*Pointer = " << *pointer << "\n";

cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26

Just as demonstrated earlier, after initializing a pointer, if you change the value of the variable it points to, the pointer would be updated. Consider the following program:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

pointer = &value; pointerToPointer = &pointer;

cout << " cout << "

Value

= " << value << "\n";

*Pointer = " << *pointer << "\n";

cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "After changing the value of the main variable...\n"; cout << " cout << " Value = " << value << "\n";

*Pointer = " << *pointer << "\n";

cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26 After changing the value of the main variable...

Value

= 4805

*Pointer = 4805 **Pointer = 4805

Notice that, by changing the value of the original variable, when accessing its pointer or the pointer to its pointer, they reflect the new value. In the same way, instead of (directly) changing the value of the variable, you can change the value of its pointer. You can also change the value of the pointer to its pointer. Like a chain reaction, all variables would be updated. Consider the following program:
#include <iostream> using namespace std;

int main() { int value = 26; int *pointer; int **pointerToPointer;

pointer = &value; pointerToPointer = &pointer;

cout << "

Value

= " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

value = 4805;

cout << "\nAfter changing the value of the main variable...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

*pointer = -728;

cout << "\nAfter changing the value of the pointer...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

**pointerToPointer = 945580;

cout << "\nAfter changing the value of the pointer to pointer...\n"; cout << " Value = " << value << "\n";

cout << " *Pointer = " << *pointer << "\n"; cout << "**Pointer = " << **pointerToPointer << "\n";

return 0; }

This would produce:


Value = 26

*Pointer = 26 **Pointer = 26

After changing the value of the main variable... Value = 4805

*Pointer = 4805 **Pointer = 4805

After changing the value of the pointer...

Value

= -728

*Pointer = -728 **Pointer = -728

After changing the value of the pointer to pointer... Value = 945580

*Pointer = 945580 **Pointer = 945580

Operations on Pointers Introduction Consider that, added just a few rules, a pointer is a variable like any other: it can get its value from the user (indirectly), you can apply any of the algebraic operations we have learned, it can be incremented, it can be applied on a function, etc. A variable is a value that is supposed to change some time to time. Since a pointer is a variable whose value points to another variable, the value of a pointer is affected by the variable it points to. You can use this indirection to change the value of a pointer when changing its main variable. To get a value from the user, we have already learned that you can use the cin operator. When using a pointer to get a value from the user, don't forget the * operator, otherwise, the compiler would get confused. We have already learned how to request and display the value of a regular variable from the user:
#include <iostream> using namespace std;

int main() { int students;

cout << "Number of students: "; cin >> students;

cout << "\nNumber of students: " << students;

cout << "\n\n"; return 0; }

Once you have gotten a value and store it in a variable, it is available:


#include <iostream> using namespace std;

int main() { int students; int *ptrStudents;

ptrStudents = &students; cout << "Number of students: "; cin >> students; cout << "\nNumber of students: " << students << "\nThat is: " << *ptrStudents << " students."; cout << "\n\n"; return 0; }

This could produce:


Number of students: 24

Number of students: 24 That is: 24 students

In the same way, you can request a value from the user and store it in the pointer. To see an example, make the following change to the file:
#include <iostream> using namespace std;

int main() { int students; int *ptrStudents;

ptrStudents = &students; cout << "Number of students: "; cin >> *ptrStudents;

cout << "\nNumber of students: " << students << "\nThat is: " << *ptrStudents << " students.";

cout << "\n\n"; return 0; }

Of course, you can use various pointers on the same program. Apply an example by making the following changes:
#include <iostream> using namespace std;

int main() { int boys;

int girls; int *ptrBoys; int *ptrGirls;

ptrBoys = &boys; ptrGirls = &girls;

cout << "Number of male students: "; cin >> *ptrboys;

cout << "Number of female students: "; cin >> *ptrGirls; cout << "\nNumber of students:";

cout << "\nBoys:" << "\t" << Boys << "\nThat is: " << *ptrBoys << " students."; cout << "\nGirls:" << "\t" << Girls << "\nThat is: " << *ptrGirls << " students.";

cout << "\n\n"; return 0; }

We have learned how to perform algebraic calculations and expressions in C++. When performing these operations on pointers, remember to use the * for each pointer involved. The calculations should be as smooth:
#include <iostream> using namespace std;

int main() { int boys; int girls; int total; int *ptrBoys; int *ptrGirls; int *ptrTotal;

ptrBoys = &boys; ptrGirls = &girls; ptrTotal = &total;

cout << "Number of male students: "; cin >> *ptrBoys; cout << "Number of female students: "; cin >> *ptrGirls;

cout << "\nNumber of students:"; cout << "\nBoys:" << "\t" << Boys << "\nThat is: " << *ptrBoys << " students."; cout << "\nGirls:" << "\t" << Girls << "\nThat is: " << *ptrGirls << " students.";

Total = Boys + Girls;

*ptrTotal = *ptrBoys + *ptrGirls;

cout << "\n\nTotal number of students: " << total; cout << "\nThere are " << *ptrTotal << " students";

cout << "\n\n"; return 0; }

This would produce:


Number of male students: 26 Number of female students: 24

Boys: 26 That is: 26 students Girls: 24 That is: 24 students

Total number of students: 50 There are 50 students

Passing Pointers to Functions We know that a function uses arguments in order to carry its assignment. The arguments are usually provided to the function. When necessary, a function also declares its own variable to get the desired return value. Like other variables, pointers can be provided to a function, with just a few rules. When declaring a function that takes a pointer as an argument, make sure you use the asterisk for the argument or for each argument. When calling the function, use the references to the variables. The function will perform its assignment on the referenced variable(s). After the function has performed its assignment, the changed value(s) of the argument(s) will be preserved and given to the calling function. Here is a starting file from what we have learned so far:
#include <iostream> using namespace std;

int main() { int shirts = 12; int pants = 5;

cout << "Shirts = " << shirts << endl; cout << "Pants = " << pants << endl;

cout << endl; return 0; }

This would produce:


Shirts = 12 Pants = 5

To pass arguments to a function, you can make the following changes:


#include <iostream> using namespace std;

int main() { int shirts = 3; int pants = 5; void Deposit(int s, int p);

cout << "When starting, within main():\n"; cout << "\tShirts = " << shirts << endl;

cout << "\tPants

= " << pants << endl;

Deposit(Shirts, Pants);

cout << "\n\nAfter calling Deposit(), within main():\n"; cout << "\tShirts = " << shirts << endl;

cout << "\tPants cout << endl; return 0; }

= " << pants << endl;

void Deposit(int s, int p) { s = 8; p = 12;

cout << "Within Deposit()" << "\n\tShirts = " << s << "\n\tPants } = " << p;

After executing, the program would produce:


When starting, within main(): Shirts = 3 Pants = 5

Within Deposit() Shirts = 8 Pants = 12

After calling Deposit(), Within main(): Shirts = 3 Pants = 5

To pass pointer arguments, use the asterisks when declaring the function, and use the ampersand & when calling the function. Here is an example:
#include <iostream> using namespace std;

int main() { int shirts = 12; int pants = 5; void Deposit(int s, int p); void Pickup(int *sht, int *pt);

cout << "When starting, within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

Deposit(shirts, pants); cout << "\n\nAfter calling Deposit(), within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

Pickup(&shirts, &pants); cout << "\n\nAfter calling Pickup(), within main():\n"; cout << "\tShirts = " << shirts << endl; cout << "\tPants = " << pants << endl;

cout << endl; return 0; }

void Deposit(int s, int p) { s = 8; p = 5;

cout << "\nWithin Deposit()" << "\n\tShirts = " << s << "\n\tPants } = " << p;

void Pickup(int *sht, int *pt) { *sht *pt = 17; = 26;

cout << "\nWithin Pickup()" << "\n\tShirts = " << *sht << "\n\tPants } = " << *pt;

The result of executing the program is:


When starting, within main(): Shirts = 12 Pants = 5

Within Deposit()

Shirts = 8 Pants = 5

After calling Deposit(), within main(): Shirts = 12 Pants = 5

Within Pickup() Shirts = 26 Pants = 17

After calling Pickup(), within main(): Shirts = 26 Pants = 17

A Function That Returns a Pointer If you want a function to return a pointer, when declaring the function, make sure that you specify its return type as a pointer and you can use a type of your choice. Here is an example of such a declaration:
#include <iostream> using namespace std;

int main() { int *GetNumber();

return 0; }

In this case, we have declared a function named GetNumber that will return a pointer to int. When implementing the function, you can apply any of the techniques we have used so far inside the

function. The most important rule to keep in mind is that the function must return a pointer and not a regular value. In the same way, when calling a function that returns a pointer, you can use its value only where the returned pointer is appropriate. For example, you can assign its returned value only to a pointer of the same type. Here is an example:
#include <iostream> using namespace std;

int main() { int *GetNumber(); int *number;

number = GetNumber();

cout << "Number = " << *number << endl; return 0; }

int *GetNumber() { int *a = new int(2885);

return a; }

This would produce:


Number = 2885

Pointers and Memory Management By definition, the variables in your program are meant to "vary", that is, their values change

regularly. When you declare a variable, such as


int Shirts;

the compiler reserves an appropriate amount of memory space for that particular variable. This is done when the program is compiling but before its execution. This means of providing memory space is called static allocation, the memory space is "allocated" to that variable. When the program executes, this static memory allocation does not change; but the memory space might be empty, especially if the variable is not initialized. This is important: the fact that a variable is not initialized means its memory space is empty, it is not equal to zero; it is simply empty. Nothing is occupying it. You can also ask the compiler to provide memory when the program is executing. This is called dynamic allocation. Dynamic allocation is performed using the new operator like this:
PointerName = new DataType;

The keyword new is required. The data type can be any of those we are already familiar with, but it must be appropriate to the variable it is pointing to. This means that, if it is pointing to an integer variable, the data type must be an integer. For example, our corresponding dynamic allocation would be:
ptrShirts = new int;

After dynamically allocating memory, you can assign a new value to the pointer for any purpose. Once the memory is not anymore in use, you should reclaim it. This is done with the delete keyword, like this:
delete ptrShirts;

Here is a starting point for this section :


#include <iostream> using namespace std;

int main() { int studentAge = 12;

cout << "Student age = " << studentAge << endl;

cout << endl; return 0; }

Now, let's add a pointer and try to access it without initializing it:
#include <iostream> using namespace std;

int main() { int studentAge = 12; int* age;

cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

cout << endl; return 0; }

You will get a value that is not insignificant. Depending on the compiler, you might even get a nasty dialog box and a warning. This is because you were trying to access a pointer that has not been initialized. You can initialize the pointer like this:
#include <iostream> using namespace std;

int main() { int studentAge = 12; int* age;

Age = &studentAge;

cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

cout << endl; return 0; }

To illustrate that an un-initialized variable has an address (although empty), you can change the file as follows:
#include <iostream> using namespace std;

int main() { int studentAge; int* ptrAge;

ptrAge = &studentAge;

cout << "Student age = " << studentAge << endl; cout << "*ptrAge = " << *ptrAge << endl;

cout << endl; return 0; }

When you initialize a variable, its value gets stored in the memory space that was statically allocated by the compiler. In the same way, since its corresponding pointer points to its address, you can initialize the pointer and still access the value assigned to the variable it is pointing to. To see an

example of a pointer, and not the variable itself being initialized, make the following changes to the file:
#include <iostream> using namespace std;

int main() { int studentAge; int *age;

age = &studentAge; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

*Age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; return 0; } = " << *age << endl;

This results in:


Student age = -858993460 *Age Student age = 15 *Age = 15 = -858993460

To dynamically allocate memory, you assign the pointer with the new keyword followed by the appropriate identifier:
#include <iostream> using namespace std;

int main() { int studentAge; int *age;

age = &studentAge; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

*age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl;

age = new int; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; return 0; } = " << *age << endl;

As you can see, since the value of the pointer has been dynamically assigned, its address is now empty. If you want to access its content, you have to reassign it another value; this is one of the mistakes that happen regularly in a program. When this happens, the program will compile fine, without any error or warning, but the result Therefore, you should always know the value of a pointer. In our example, you can reassign a value to the empty pointer:
age = new int; *Age = 17; cout << "Student age = " << studentAge << endl; cout << "*Age cout << "\n"; } = " << *age << endl;

After using a pointer, don't forget to clean your memory. You do this using the delete operator:
#include <iostream.h> int main() { int studentAge; int *age; age = &studentAge; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; *age = 15; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; Age = new int; *age = 17; cout << "Student age = " << studentAge << endl; cout << "*Age = " << *age << endl; delete age; cout << "\n"; return 0; }

Arrays and Pointers The Relationship Between a Pointer and an Array Introduction Here is an example of an array as we learned when studying them:
#include <iostream> using namespace std; int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout cout cout cout << << << << "List of Numbers"; "\nNumber 1: " << number[0]; "\nNumber 2: " << number[1]; "\nNumber 3: " << number[2];

cout cout cout cout cout cout cout cout cout }

<< << << << << << << << <<

"\nNumber "\nNumber "\nNumber "\nNumber "\nNumber "\nNumber "\nNumber "\nNumber "\nNumber

4: 5: 6: 7: 8: 9: 10: 11: 12:

" " " " " " " " "

<< << << << << << << << <<

number[3]; number[4]; number[5]; number[6]; number[7]; number[8]; number[9]; number[10]; number[11];

return 0;

In this case, the Number variable is an array of 12 integer values. Because a variable declared as array is first of all a variable, using its name, let us find its address. Consider the following program:
#include <iostream> using namespace std; int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; cout << "\n Number : cout << "\n&Number : cout << "\n&number[0] : return 0; } " << Number; " << &Number; " << &number[0] << endl;

This would produce:


Number &Number : : 1245020 1245020 1245020

&number[0] :

This demonstrates that Number, &Number, and &number[0] have the same value. As we learned with pointers, the use of the ampersand "&" allows us to get the address of a variable. Therefore, &Number gives us the address of the array variable. Furthermore, since &Number and &number[0] have the same value, and seeing that all three (Number, &Number, and &number[0]) have the same value, this demonstrates that the name of the variable in fact carries, or holds, or represents, the address of the first value of the array. In fact, consider the following program:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

cout << "An integer occupies " << sizeof(int) << " bytes\n"; cout << "\n Number: " << Number;

cout << "\n&number[0]: " << &number[0] << endl; cout << "\n Number+1: " << Number+1;

cout << "\n&Number:[1] " << &number[1] << endl; cout << "\n Number+2: " << Number+2;

cout << "\n&Number:[2] " << &number[2] << endl;

return 0; }

This would produce:


An integer occupies 4 bytes

Number:

1245020

&number[0]: 1245020

Number+1:

1245024

&Number:[1] 1245024

Number+2:

1245028

&Number:[2] 1245028

Notice that, by adding numbers to the name of the variable, we are able to get the address of any

member of the array. Relating a Pointer to an Array Now that we know that the name of an array holds the address of the first member of the array, we realize that we can declare a pointer of the same data type as the array and initialize it with the array. Here is an example:
int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

After this declaration and initialization, Number and pNumbers have the same value:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Addresses"; cout << "\n Number : " << Number; " << pNumbers;

cout << "\npNumbers :

return 0; }

This would produce:


Addresses Number : 1245020 1245020

pNumbers :

In other words, pNumbers points to the beginning of the array. As you can see from the previous result, pNumbers holds an address and not a value, that is, not the value of the first member of the

array. Since pNumbers points to the first member of the array (by virtue of its relationship to the array, which we have demonstrated by showing that pNumbers and Number hold the same value, which is the same as the address of the first member of the array), to get the value that pNumbers holds, we learned, when studying pointers, that you must use the asterisk operator. Therefore, number[0], which is the value of the first member of the array, is the same as *pNumbers, which is the value of the first member of the array. This can be verified in the following program:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Values"; cout << "\n number[0] : : " << number[0]; " << *pNumbers;

cout << "\n*pNumber

return 0; }

This would produce:


Values number[0] : *pNumber : 31 31

We saw already that pNumbers is an address; it is not a value. In the same way, Number is an address. To get the value of a member of the Number array, we know that, using the square brackets, we can provide the index of the member we want and retrieve its value. In the same way, using a pointer that has been initialized to an array variable, we can use the square bracket and the index of the member whose value we want to retrieve. This is demonstrated in the following program:

#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Addresses"; cout << "\n Number : " << Number; " << pNumbers;

cout << "\npNumbers :

cout << "\n\nValues"; cout << "\n Number [0] : cout << "\npNumbers[0] : cout << "\n Number [1] : cout << "\npNumbers[1] : " << number[0]; " << pNumbers[0]; " << number[1]; " << pNumbers[1];

return 0; }

This would produce:


Addresses Number : 1245020 1245020

pNumbers :

Values

Number [0] : pNumbers[0] : Number [1] : pNumbers[1] :

31 31 28 28

At this time, we know how to get the address of the first member of the array, with either Number or pNumbers. To get the address of the second member of the array, we increment that address value, as in Number+1. Since Number is an address and not a value, adding 1 to it adds the size of its type, in this case 4 bytes, in order to get to the next address. In the same way, using a pointer that has been initialized with an array, to get the address of the next member of the array, simply increment its name. Here is an example:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Addresses"; cout << "\n Number cout << "\npNumbers : : " << Number; " << pNumbers; " << Number+1; " << pNumbers+1; " << Number+2; " << pNumbers+2;

cout << "\n Number +1 : cout << "\npNumbers+1 : cout << "\n Number +2 : cout << "\npNumbers+2 :

return 0; }

This would produce:


Addresses Number pNumbers : : 1245020 1245020 1245024 1245024 1245028 1245028

Number +1 : pNumbers+1 : Number +2 : pNumbers+2 :

Now we know that by writing pNumbers or pNumbers+n, we get the address of the member that "lives" at pNumbers or pNumbers+n. We already saw that, by writing *pNumbers, we can get the value of the first member of the array. When writing *pNumbers, we are in fact asking the compiler to retrieve the value that pNumbers points to. If we want to get the value of the next member of the array, we must first give its address, which is done by adding the index of the member of the array to pNumbers. Once we have communicated the address, we use the asterisk operator to retrieve the actual value of the member of the array. Because the asterisk operator has a higher precedence than the addition operator, to get the address before the value, you must use parentheses to delimit the operation:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number;

cout << "Values - Using the Array"; cout << "\n number[0]: cout << "\n number[1]: cout << "\n number[2]: " << number[0]; " << number[1]; " << number[2];

cout << "\n number[3]: cout << "\n number[4]:

" << number[3]; " << number[4];

cout << "\n\nValues - Using the Pointer - No Parentheses"; cout << "\n*pNumbers: cout << "\n*pNumbers+1: cout << "\n*pNumbers+2: cout << "\n*pNumbers+3: cout << "\n*pNumbers+4: " << *pNumbers; " << *pNumbers+1; " << *pNumbers+2; " << *pNumbers+3; " << *pNumbers+4;

cout << "\n\nValues - Using the Pointer - With Parentheses"; cout << "\n*pNumbers: " << *pNumbers;

cout << "\n*(pNumbers+1): " << *(pNumbers+1); cout << "\n*(pNumbers+2): " << *(pNumbers+2); cout << "\n*(pNumbers+3): " << *(pNumbers+3); cout << "\n*(pNumbers+4): " << *(pNumbers+4);

return 0; }

This would produce:


Values - Using the Array number[0]: number[1]: number[2]: number[3]: number[4]: 31 28 31 30 31

Values - Using the Pointer - No Parentheses

*pNumbers: *pNumbers+1: *pNumbers+2: *pNumbers+3: *pNumbers+4:

31 32 33 34 35

Values - Using the Pointer - No Parentheses *pNumbers: 31

*(pNumbers+1): 28 *(pNumbers+2): 31 *(pNumbers+3): 30 *(pNumbers+4): 31

Press any key to continue...

Therefore, as long as you increment the address of the variable, you can use a for loop to navigate the array to get the value of each member of the array:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number; int numberOfMembers = sizeof(Number) / sizeof(int);

cout << "List of Numbers"; for(int i = 0; i < NumberOfMembers; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

return 0; }

A Pointer as Argument Introduction As we have seen so far, a function can use one or more arguments in order to carry its assignment. When necessary, a function also declares its own variable(s) to get the desired return value. A variable declared in the body of a function is referred to as a local variable. Here is an example:
#include <iostream> using namespace std;

double

CalculateNetPrice(double disc);

int main() { double finalPrice; double discount = 20;

finalPrice = CalculateNetPrice(discount);

cout << "\nAfter applying a 20% discount"; cout << "\nFinal Price = " << finalPrice << "\n";

return 0; }

double {

CalculateNetPrice(double d)

double origPrice;

cout << "Please enter the original price: "; cin >> origPrice;

return origPrice - (origPrice * d / 100); }

Here is an example of running the program:


Please enter the original price: 125.55

After applying a 20% discount Final Price = 100.44 Press any key to continue

Like other variables, a pointer can be passed to a function. When declaring and when implementing a function that takes a pointer as an argument, use the asterisk for the argument or for each argument. Here is an example:
#include <iostream> using namespace std;

double

CalculateNetPrice(double *disc);

int main() {

return 0; }

double {

CalculateNetPrice(double *discount)

double origPrice;

cout << "Please enter the original price: "; cin >> origPrice;

return origPrice - (origPrice * *discount / 100); }

When calling the function, use the reference(s) to the variable(s). The function will perform its assignment on the referenced variable(s). After the function has performed its assignment, the changed value(s) of the argument(s) will be preserved and given to the calling function. Here is an example:
int main() { double finalPrice; double discount = 20;

finalPrice = CalculateNetPrice(&discount);

cout << "\nAfter applying a 20% discount"; cout << "\nFinal Price = " << finalPrice << "\n";

return 0; }

An example of running the program is:


Please enter the original price: 100

After applying a 20% discount Final Price = 80

Practical Learning: Passing Pointers as Arguments 1. Create a new project named Fire Insurance2 2. Create a C++ source file named Main.cpp 3. Change the Main.cpp file as follows:

#include <iostream> using namespace std;

double GetAnnualPremium(); double GetCoverage(); double GetPolicy(); double CalculatePremium(double Rt, double Cvr, double Plc);

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; Rate = GetAnnualPremium();

Coverage = GetCoverage(); Policy = GetPolicy();

Premium = CalculatePremium(Rate, Coverage, Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

double GetAnnualPremium() { double AnlPrem;

cout << "Enter the annual premium: $"; cin >> AnlPrem; return AnlPrem; }

double GetCoverage() { double Cover;

cout << "Enter the coverage: $"; cin >> Cover; return Cover; }

double GetPolicy() { double Plc;

cout << "Enter the policy amount: $"; cin >> Plc; return Plc;

double CalculatePremium(double Rate, double Cover, double Pol) { double Prem; int Unit;

Unit = Pol / Cover; Prem = Rate * Unit; return Prem; }

4. Test the program. Here is an example:

Fire Insurance - Customer Processing Enter the annual premium: $0.55 Enter the coverage: $92 Enter the policy amount: $45000

******************************** Fire Insurance - Customer Quote ________________________________ Annual Premium: $0.55 Coverage: Policy: Premium: $92 $45000 $268.95

********************************

5. Return to your programming environment

6. To process arguments as pointers and call the CalculatePremium() function within main(), change the program as follows:

#include <iostream> using namespace std;

double CalculatePremium(double *Rt, double *Cvr, double *Plc);

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; cout << "Enter the annual premium: $"; cin >> Rate; cout << "Enter the coverage: cout << "Enter the policy amount: $"; cin >> Coverage; $"; cin >> Policy;

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

double CalculatePremium(double *Rate, double *Cover, double *Pol) { double Prem; int Unit;

Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; }

7. Test the application and return to your programming environment The Effect of Passing a Pointer as Argument Consider the following program:
#include <iostream> using namespace std;

void GetTheOriginalPrice(double OrigPrice);

int main() { double OriginalPrice = 0;

cout << "First in main() --";

cout << "\nOriginal Price =

$" << OriginalPrice << endl;

GetTheOriginalPrice(OriginalPrice);

cout << "\nBack in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

return 0; }

void GetTheOriginalPrice(double OrigPrice) { cout << "\nNow we are in the GetTheOriginalPrice() function"; cout << "\nPlease enter the original price: "; cin >> OrigPrice;

cout << "\nIn the GetTheOriginalPrice() function"; cout << "\nOriginal Price = $" << OrigPrice << endl; }

Here is an example of running the program:


First in main() -Original Price = $0

Now we are in the GetTheOriginalPrice() function Please enter the original price: 100

In the GetTheOriginalPrice() function Original Price = $100

Back in main() -Original Price = $0

Notice that the value of the OriginalPrice variable is kept intact in the main() function, as 0, before and after calling the GetTheOriginalPrice() function. Like a reference, when passing a pointer as argument to a function, the function that is receiving the argument is in fact accessing the argument's address. Therefore, like a reference, the called function has the ability to alter the value held by the pointer. The effect is the same as for the reference: if the called function modifies the value of the pointer, that value is permanently changed. This is a feature you can use to your advantage. This effect is illustrated in the following program:
#include <iostream> using namespace std;

void GetTheOriginalPrice(double *OrigPrice);

int main() { double OriginalPrice = 0;

cout << "First in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

GetTheOriginalPrice(&OriginalPrice);

cout << "\nBack in main() --"; cout << "\nOriginal Price = $" << OriginalPrice << endl;

return 0; }

void GetTheOriginalPrice(double *OrigPrice)

{ cout << "\nNow we are in the GetTheOriginalPrice() function"; cout << "\nPlease enter the original price: "; cin >> *OrigPrice;

cout << "\nIn the GetTheOriginalPrice() function"; cout << "\nOriginal Price = $" << *OrigPrice << endl; }

Here is an example of executing this program:


First in main() -Original Price = $0

Now we are in the GetTheOriginalPrice() function Please enter the original price: 100

In the GetTheOriginalPrice() function Original Price = $100

Back in main() -Original Price = $100

Press any key to continue...

Notice that, this time, after calling the GetTheOriginalPrice() function, the value of the OriginalPrice variable is permanently changed and the second time it is accessed in the main() function, it holds a different value than the first time it was called.

Practical Learning: Passing Reference Pointers to Functions

1. To process variables by passing them as reference pointers, change the Main.cpp file as follows:

#include <iostream> using namespace std;

void GetAnnualPremium(double *Prem); void GetCoverage(double *Cvr); void GetPolicy(double *Plc); double CalculatePremium(double *Rt, double *Cvr, double *Plc);

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; GetAnnualPremium(&Rate); GetCoverage(&Coverage); GetPolicy(&Policy);

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________"; cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

void GetAnnualPremium(double *AnlPrem) { cout << "Enter the annual premium: $"; cin >> *AnlPrem; }

void GetCoverage(double *Cover) { cout << "Enter the coverage: $"; cin >> *Cover; }

void GetPolicy(double *Plc) { cout << "Enter the policy amount: $"; cin >> *Plc; }

double CalculatePremium(double *Rate, double *Cover, double *Pol) { double Prem; int Unit;

Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; }

2. Test the application. Here is an example:

Fire Insurance - Customer Processing Enter the annual premium: $0.74 Enter the coverage: $120 Enter the policy amount: $60000

******************************** Fire Insurance - Customer Quote ________________________________ Annual Premium: $0.74 Coverage: Policy: Premium: $120 $60000 $370

********************************

Press any key to continue...

3. Return to your programming environment Constant Pointers as Arguments The previous section demonstrates to us that, when passing a pointer as argument, the effect is the same as passing an argument as reference. This shows that, passing a pointer as argument gives the called function direct access to the address of the variable. Besides permanently changing the value of the argument, this process also speeds up code execution because the called function does not deal with a copy of the variable but the variable itself. Although there are various good reasons to pass pointers as arguments, sometimes you may not want the called function to modify the value held by

the variable. In fact you can prevent this. If a function that receives a pointer as argument is not supposed to modify the value of the argument, you can pass the argument as a constant pointer. To do this, type the const keyword on the left side of the data type of the pointer argument. Here is an example:
#include <iostream> using namespace std;

double

CalculateNetPrice(const double *Disc);

int main() { double FinalPrice; double Discount = 20;

FinalPrice = CalculateNetPrice(&Discount);

cout << "\nAfter applying a 20% discount"; cout << "\nFinal Price = " << FinalPrice << "\n";

return 0; }

double {

CalculateNetPrice(const double *Discount)

double OrigPrice;

cout << "Please enter the original price: "; cin >> OrigPrice;

return OrigPrice - (OrigPrice * *Discount / 100); }

Practical Learning: Passing Constant Pointers 1. To pass arguments as constant pointers, change the CalculatePremium() function as follows:

#include <iostream> using namespace std;

void GetAnnualPremium(double *Prem); void GetCoverage(double *Cvr); void GetPolicy(double *Plc); double CalculatePremium( const double *Rt, const double *Cvr, const double *Plc );

int main() { double Rate, Coverage, Policy, Premium;

cout << "Fire Insurance - Customer Processing\n"; GetAnnualPremium(&Rate); GetCoverage(&Coverage); GetPolicy(&Policy);

Premium = CalculatePremium(&Rate, &Coverage, &Policy);

cout << "\n********************************"; cout << "\nFire Insurance - Customer Quote"; cout << "\n________________________________";

cout << "\nAnnual Premium: $" << Rate; cout << "\nCoverage: cout << "\nPolicy: cout << "\nPremium: $" << Coverage; $" << Policy; $" << Premium;

cout << "\n********************************\n";

return 0; }

void GetAnnualPremium(double *AnlPrem) { cout << "Enter the annual premium: $"; cin >> *AnlPrem; }

void GetCoverage(double *Cover) { cout << "Enter the coverage: $"; cin >> *Cover; }

void GetPolicy(double *Plc) { cout << "Enter the policy amount: $"; cin >> *Plc; }

double CalculatePremium( const double *Rate, const double *Cover,

const double *Pol ) { double Prem; int Unit;

Unit = *Pol / *Cover; Prem = *Rate * Unit; return Prem; }

2. Test the application and return to your programming environment 3. Save All Pointers and Multi-Dimensional Arrays From our study of multidimensional arrays, we know how to create a two-dimension array as follows:
#include <iostream>

using namespace std;

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } };

cout << "List of Numbers"; for(int i = 0; i < 2; i++) for(int j = 0; j < 6; j++) cout << "\nNumber [" << i << "][" << j << "]: " << number[i][j];

return 0; }

In this case, Number is a variable that represents 2 groups of 6 integers each. From our first lesson on pointers, we saw that a pointer is simply created by providing a data type, followed by an asterisk, and followed by the name of the variable. Here is an example:
int *pNumbers;

We also established that this declaration by itself gives way to an array after an initialization. This means that we can safely assign the name of an array to the pointer and the pointer would be initialized. Since *pNumbers in this example is first of all a variable, to declare an array of this variable, simply add a dimension and the necessary square brackets required to declare any array. This can be done as follows:
int *pNumbers[2];

This declaration creates two pointers, and each pointer points to an array of integers. After this declaration, you can initialize each pointer as you see fit. In fact, each pointer can point to an array of a different dimension. This means that one pointer can point to an array of 15 members and another pointer from this declaration can point to an array of 68 members. You have the choice. Since the compiler cannot predict and cannot decide on the number of members of each array, it is your responsibility to communicate this. If you want to use the members of an existing array to initialize the pointer, first specify which pointer you want to initialize, using its index. To access the first pointer, you would type *(pNumbers+0), which is the same as *(pNumbers) or *pNumbers. The second pointer can be accessed with *(pNumbers+1). Once you have specified which pointer you are interested in, you can initialize it with the desired dimension of the array. For a two-dimensional array, you would be initializing the pointer with the corresponding column, that is, the second index of the array. Here is an example:

*(pNumbers+1) = number[3];

In this case, the second pointer points to the array that is the second column of the Number variable. Keep in mind that, this time, *pNumbers is a pointer and not a value. Therefore, to access a member of the array, you must first specify the desired pointer. Then, using its index, you can get the corresponding value. Here is an example:
#include <iostream>

using namespace std;

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } }; int *pNumbers[2];

*pNumbers = number[0]; (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = number[0][0]; = number[0][1]; = number[0][2]; = number[0][3]; = number[0][4]; = number[0][5];

*(pNumbers+1) = number[1]; (*(pNumbers+1))[0] = number[1][0];

(*(pNumbers+1))[1] = number[1][1]; (*(pNumbers+1))[2] = number[1][2]; (*(pNumbers+1))[3] = number[1][3]; (*(pNumbers+1))[4] = number[1][4]; (*(pNumbers+1))[5] = number[1][5];

cout << "List of Numbers"; cout << "\n(*pNumbers)[0] cout << "\n(*pNumbers)[1] cout << "\n(*pNumbers)[2] cout << "\n(*pNumbers)[3] cout << "\n(*pNumbers)[4] cout << "\n(*pNumbers)[5] = " << (*pNumbers)[0]; = " << (*pNumbers)[1]; = " << (*pNumbers)[2]; = " << (*pNumbers)[3]; = " << (*pNumbers)[4]; = " << (*pNumbers)[5] << endl;

cout << "\n(*(pNumbers+1))[0] = " << (*(pNumbers+1))[0]; cout << "\n(*(pNumbers+1))[1] = " << (*(pNumbers+1))[1]; cout << "\n(*(pNumbers+1))[2] = " << (*(pNumbers+1))[2]; cout << "\n(*(pNumbers+1))[3] = " << (*(pNumbers+1))[3]; cout << "\n(*(pNumbers+1))[4] = " << (*(pNumbers+1))[4]; cout << "\n(*(pNumbers+1))[5] = " << (*(pNumbers+1))[5] << endl;

return 0; }

This would produce:


List of Numbers

(*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5]

= 31 = 28 = 31 = 30 = 31 = 30

(*(pNumbers+1))[0] = 31 (*(pNumbers+1))[1] = 31 (*(pNumbers+1))[2] = 30 (*(pNumbers+1))[3] = 31 (*(pNumbers+1))[4] = 30 (*(pNumbers+1))[5] = 31

Press any key to continue...

Dynamic Arrays Allocating Memory Based on this relationship between arrays and pointers, you can use the new operator to dynamically create an array. This has the advantage of allowing you to allocate the desired amount of space and getting rid of it once not needed anymore. The syntax of dynamically creating an array of pointers is:
DataType *ArrayName = new DataType[Dimensions];

To start, type the kind of array you want to create: this is the DataType. The ArrayName is a regular name you want to give to the variable. Since this is a pointer, the array name must be preceded by an asterisk operator. Assign the new operator to the array name. The new operator is followed by the same kind of data type of the first parameter, DataType. The the necessary number of members of the array as the Dimension. This Dimension is included

between square brackets, as every array. Here are examples of dynamic arrays:
double *Distance = new double[12]; unsigned int *pRanges = new unsigned int[120]; float *Prices = new float[44];

After dynamically creating an array, the compiler allocates the necessary memory space for all the members of the array, based on the data type and accommodating each. Just like any variable, the memory allocated for each member of the array contains garbage. It is your responsibility to fill it up for appropriate values. This can be taken care of by assigning a value to each member of the array. Each member of the array can be accessed by using its index on the name of the array. You have two options. You can apply the index of an array member on the name of the pointer. Here is an example:
int *pNumbers = new int[12];

pNumbers[0] = 31; pNumbers[1] = 29; pNumbers[2] = 31; pNumbers[3] = 30;

You can also access the address of the desired member, then assign it a value. Here is an example:
int *pNumbers = new int[12];

*(pNumbers+4) = 31; *(pNumbers+5) = 30; *(pNumbers+6) = 31; *(pNumbers+7) = 31;

In the same way, you can use either method to retrieve the value of a member of the array:
#include <iostream> using namespace std;

int main() { int *pNumbers = new int[12];

pNumbers[0] pNumbers[1] pNumbers[2] pNumbers[3] *(pNumbers+4) *(pNumbers+5) *(pNumbers+6) *(pNumbers+7) *(pNumbers+8) *(pNumbers+9)

= 31; = 29; = 31; = 30; = 31; = 30; = 31; = 31; = 30; = 31;

pNumbers[10] = 30; pNumbers[11] = 31;

cout << "List of numbers"; cout << "\nNumber 1: cout << "\nNumber 2: cout << "\nNumber 3: cout << "\nNumber 4: cout << "\nNumber 5: cout << "\nNumber 6: cout << "\nNumber 7: cout << "\nNumber 8: cout << "\nNumber 9: " << *pNumbers; " << *(pNumbers+1); " << *(pNumbers+2); " << *(pNumbers+3); " << pNumbers[4]; " << pNumbers[5]; " << pNumbers[6]; " << pNumbers[7]; " << *(pNumbers+8);

cout << "\nNumber 10: " << *(pNumbers+9); cout << "\nNumber 11: " << pNumbers[10]; cout << "\nNumber 12: " << pNumbers[11];

return 0; }

This would produce:


List of numbers Number 1: Number 2: Number 3: Number 4: Number 5: Number 6: Number 7: Number 8: Number 9: 31 29 31 30 31 30 31 31 30

Number 10: 31 Number 11: 30 Number 12: 31

Press any key to continue...

Disposing of Memory

After using a pointer that was pointing to an array, when you do not need it anymore, you should delete it from memory and reclaim the space it was using. This is done using the delete operator. The syntax used is:
delete [] VariableName;

The required delete operator is used to let the compiler know that you want to delete a pointer variable that was pointing to an array. The delete keyword is followed by empty square brackets. These brackets allow the compiler to know that you are deleting a pointer to an array. You must use the square brackets and they must be empty. The VariableName must be the name of the pointer. Here is an example:
#include <iostream>

using namespace std;

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = Number; int numberOfMembers = sizeof(Number) / sizeof(int);

cout << "List of Numbers"; for(int i = 0; i < NumberOfMembers; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

delete [] pNumbers;

return 0; }

This operation is usually performed on a dynamically created array, that is, on a pointer that was used to create an array. The formula is the same: after using the dynamic array, delete the pointer using the delete operator. To avoid memory leak, you can also assign NULL to the name of the array. Here is an example
#include <iostream>

using namespace std;

int main() { const int Size = 12; int *pNumbers = new int[Size];

pNumbers[0] pNumbers[1] pNumbers[2] pNumbers[3] *(pNumbers+4)

= 31; = 28; = 31; = 30; = 31;

*(pNumbers+5) *(pNumbers+6) *(pNumbers+7) *(pNumbers+8) *(pNumbers+9)

= 30; = 31; = 31; = 30; = 31;

pNumbers[10] = 30; pNumbers[11] = 31;

cout << "List of numbers"; for(int i = 0; i < Size; i++) cout << "\nNumber " << i + 1 << ": " << *(pNumbers+i);

delete [] pNumbers; pNumbers = NULL;

return 0; }

Dynamic Multi-Dimensional Arrays As done with the two-dimension array, to declare a pointer to a multi-dimensional array, type a name for the variable, preceded by the pointers type and the asterisk operator. To make it an array, make sure you specify its dimension. Here is an example:
int *pNumbers[2];

Since this creates two pointers, and each pointer is an array, you must initialize each pointer. This can be done using the new operator and following the same syntax used previously. For example, to specify the first pointer as an array of 8 members, you would type:
*pNumbers = new int[8];

To provide a value to a member of the array, provide the address of its pointer and specify its index. After using a pointer, you should make sure you delete it and reclaim the memory it was using. This can be summarized as follows:
#include <iostream>

using namespace std;

int main() { int *pNumbers[2];

*pNumbers = new int[0]; (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] (*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5] = 31; = 29; = 31; = 30; = 31; = 30;

*(pNumbers+1) = new int[1]; (*(pNumbers+1))[0] = 31; (*(pNumbers+1))[1] = 31; (*(pNumbers+1))[2] = 30; (*(pNumbers+1))[3] = 31; (*(pNumbers+1))[4] = 30;

(*(pNumbers+1))[5] = 31;

cout << "List of Numbers"; cout << "\n(*pNumbers)[0] cout << "\n(*pNumbers)[1] cout << "\n(*pNumbers)[2] cout << "\n(*pNumbers)[3] cout << "\n(*pNumbers)[4] cout << "\n(*pNumbers)[5] = " << (*pNumbers)[0]; = " << (*pNumbers)[1]; = " << (*pNumbers)[2]; = " << (*pNumbers)[3]; = " << (*pNumbers)[4]; = " << (*pNumbers)[5] << endl;

cout << "\n(*(pNumbers+1))[0] = " << (*(pNumbers+1))[0]; cout << "\n(*(pNumbers+1))[1] = " << (*(pNumbers+1))[1]; cout << "\n(*(pNumbers+1))[2] = " << (*(pNumbers+1))[2]; cout << "\n(*(pNumbers+1))[3] = " << (*(pNumbers+1))[3]; cout << "\n(*(pNumbers+1))[4] = " << (*(pNumbers+1))[4]; cout << "\n(*(pNumbers+1))[5] = " << (*(pNumbers+1))[5] << endl;

delete [] *pNumbers; delete [] *(pNumbers+1);

return 0; }

This would produce;


List of Numbers (*pNumbers)[0] (*pNumbers)[1] (*pNumbers)[2] = 31 = 29 = 31

(*pNumbers)[3] (*pNumbers)[4] (*pNumbers)[5]

= 30 = 31 = 30

(*(pNumbers+1))[0] = 31 (*(pNumbers+1))[1] = 31 (*(pNumbers+1))[2] = 30 (*(pNumbers+1))[3] = 31 (*(pNumbers+1))[4] = 30 (*(pNumbers+1))[5] = 31

Press any key to continue...

Pointers and Arrays With Functions Single Dimensional Arrays and Functions When we studied arrays and functions, we saw that, to pass an array as argument to a function, you can type the name of the argument followed by parentheses. If you want to process the members of the array, you should also pass another argument that holds the number of members of the array. Here is an example:
int SumOfNumbers(int Nbr[], int Size);

When calling such a function, the name of the argument is sufficient to the compiler:
#include <iostream> using namespace std;

int {

SumOfNumbers(int Nbr[], int Size)

int Sum = 0; for(int i = 0; i < Size; i++) Sum += Nbr[i];

return Sum; }

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int numberOfMembers = sizeof(Number) / sizeof(int);

int Value = SumOfNumbers(number, numberOfMembers);

cout << "Sum of numbers: " << Value;

return 0; }

This would produce:


Sum of numbers: 365

When calling the function, the name of the array allows the compiler to pass the whole array because that name is in fact a pointer to the variable. Based on this, instead of passing an array as argument, you can instead use a pointer. We have established that, once a pointer has been initialized as holding the address of an array, the name of the array and the name of the pointer point to the same address. This means that you can also use the name of the pointer when calling such a function. Remember that the name of the pointer preceded by an asterisk is a value; therefore, you should not use it as argument when calling the function. Based on the relationship we have studied so far between pointers and arrays, the above program can also be written as follows:
#include <iostream> using namespace std;

int {

SumOfNumbers(int *nbr, int size)

int sum = 0; for(int i = 0; i < size; i++) sum += nbr[i];

return Sum; }

int main() { int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int *pNumbers = number; int numberOfMembers = sizeof(number) / sizeof(int);

int Value = SumOfNumbers(pNumbers, numberOfMembers);

cout << "Sum of numbers: " << Value;

return 0; }

This would produce the same result. Multi-Dimensional Arrays and Functions To declare a function that takes a multi-dimensional array as argument, you can type the array name followed by an empty pair of square brackets, followed by a second pair of square brackets that contain the number of columns. If you are using a pointer as argument, for example a variable that points to a two-dimensional array, provide the type of variable followed by an asterisk that indicates that the argument is a pointer, and followed by a pair of square brackets. The square brackets can be empty or contain the number of columns. Such a function can be declared as follows:

void

DisplayNumbers(int *nbr[]);

Before calling such a function, after appropriately initializing the pointer, provide only the name of the pointer. Here is an example:
#include <iostream> using namespace std; void DisplayNumbers(int *Nbr[]);

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } }; int *pNumbers[2]; *pNumbers = number[0]; (*pNumbers)[0] = number[0][0]; (*pNumbers)[1] = number[0][1]; (*pNumbers)[2] = number[0][2]; (*pNumbers)[3] = number[0][3]; (*pNumbers)[4] = number[0][4]; (*pNumbers)[5] = number[0][5]; *(pNumbers+1) = number[1]; (*(pNumbers+1))[0] = number[1][0]; (*(pNumbers+1))[1] = number[1][1]; (*(pNumbers+1))[2] = number[1][2]; (*(pNumbers+1))[3] = number[1][3]; (*(pNumbers+1))[4] = number[1][4]; (*(pNumbers+1))[5] = number[1][5]; cout << "List of Numbers"; DisplayNumbers(pNumbers); return 0; } void { DisplayNumbers(int *nbr[]) cout cout cout cout cout cout cout cout cout cout cout cout } << << << << << << << << << << << << "\n(*pNumbers)[0] "\n(*pNumbers)[1] "\n(*pNumbers)[2] "\n(*pNumbers)[3] "\n(*pNumbers)[4] "\n(*pNumbers)[5] "\n(*(pNumbers+1))[0] "\n(*(pNumbers+1))[1] "\n(*(pNumbers+1))[2] "\n(*(pNumbers+1))[3] "\n(*(pNumbers+1))[4] "\n(*(pNumbers+1))[5] = = = = = = = = = = = = " " " " " " " " " " " " << << << << << << << << << << << << (*nbr)[0]; (*nbr)[1]; (*nbr)[2]; (*nbr)[3]; (*nbr)[4]; (*nbr)[5] << endl; (*(nbr+1))[0]; (*(nbr+1))[1]; (*(nbr+1))[2]; (*(nbr+1))[3]; (*(nbr+1))[4]; (*(nbr+1))[5] << endl;

If you want to process the argument in the function where it is passed as argument and if you would not know the dimension of the array in advance, you can pass two additional arguments that represent the rows and columns of the array. Here is an example:
#include <iostream> using namespace std; void DisplayNumbers(int *Nbr[], int r, int c);

int main() { int number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } }; int *pNumbers[2]; *pNumbers = number[0]; for(int i = 0; i < 6; i++) (*pNumbers)[i] = number[0][i]; *(pNumbers+1) = number[1]; for(int i = 0; i < 6; i++) (*(pNumbers+1))[i] = number[1][i]; cout << "List of Numbers"; DisplayNumbers(pNumbers, 2, 6); return 0; }

void {

DisplayNumbers(int *nbr[], int rows, int columns)

for(int i = 0; i < rows; i++) for(int j = 0; j < columns; j++) cout << "\nNumber[" << i << "][" << j << "]: " << (*(nbr+i))[j]; }

Here is an example of executing this program:


List of Numbers

Number[0][0]: 31 Number[0][1]: 28 Number[0][2]: 31 Number[0][3]: 30 Number[0][4]: 31 Number[0][5]: 30 Number[1][0]: 31 Number[1][1]: 31 Number[1][2]: 30 Number[1][3]: 31 Number[1][4]: 30 Number[1][5]: 31

Pointers and Functions Pointers to Functions Introduction

Imagine you are writing a program to process cylinder-related calculations, that is, to get its diameter, its circumference, its areas, and volume. The formulas used are reviewed in our Geometric Formulas section. You could start your program as follows:
#include <iostream> using namespace std; int main() { double Radius; Radius = 25.55; cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; return 0; }

This would produce:


Cylinder Summary Radius: 25.55 Press any key to continue...

When we studied functions that return a value, we saw that the result of such a function can be assigned to a value locally declared in the calling function:
#include <iostream> using namespace std; int main() { double Radius, Diameter; double CalculateDiameter(double R); Radius = 25.52; Diameter = CalculateDiameter(Radius); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nDiameter: " << Diameter; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; }

At this time, we know that when a function returns a value, the calling of the function is a complete value that can be assigned to a variable. In fact, when calling a function that takes an argument, if that argument itself is gotten from a value returned by a function, the calling of the second function can be done directly when calling the first function. This seemingly complicated scenario can be easily demonstrated as follows:
#include <iostream> using namespace std; int main() { double Radius, Circumference; double CalculateDiameter(double R); double CalculateCircumference(double D); Radius = 25.52; // Instead of calling the CalculateDiameter() function first and // assign it to another, locally declared variable, such as in

// // // // // // // //

"double Diameter = CalculateDiameter(Radius)", we can call the CalculateDiameter(Radius) directly when we are calling the CalculateCircumference() function. This is possible because the CalculateCircumference() function takes an argument that is the result of calling the CalculateDiameter() function. As long as we only need the circumference and we don't need the diameter, we don't have to explicitly call the CalculateDiameter() function.

Circumference = CalculateCircumference(CalculateDiameter(Radius)); cout << "Cylinder Summary"; cout << "\nRadius: " << Radius; cout << "\nCircumference: " << Circumference << endl; return 0; } double CalculateDiameter(double Rad) { return Rad * 2; } double CalculateCircumference(double Diam) { const double PI = 3.14159; return Diam * PI; }

In some circumstances, such as this one, we may find out that the value we want to process in a function is in fact a value gotten from an intermediary function. Unfortunately, a regular function cannot be passed to a function like a regular variable. In reality, the C++ language allows this but the function must be passed as a pointer. Practical Learning: Reviewing Functions A loan is the amount of money a person or a company would borrow from another person or another company. There are various calculations involved in loan-related calculations. For example, when you borrow money from a bank, the bank applies a percentage of the amount you would pay each period of time which could be a few days, each month, each quarter, at the end of a year or after a few years. Whether you pay monthly or on another period, there is a total amount that the loan would have cost you at the end. In this and some other subsequent sections, we will review a few ways of processing loans. 1. Create a new C++ project named LoanProcessing1 2. Create a new source file named Main.cpp 3. Change the Main.cpp file as follows:

#include <iostream> using namespace std;

double GetPrincipal(); double GetInterestRate(); double GetPeriod(); int main() { double Principal, IntRate; int NumberOfPeriods; cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); NumberOfPeriods= GetPeriod(); cout cout cout cout cout cout cout cout } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } double GetPeriod() { double t; cout << "Enter the number of months: "; cin >> t; << << << << << << << << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nPrincipal: $" << Principal; "\nInterest: " << IntRate << "%"; "\nPeriod: " << NumberOfPeriods << " Months"; "\n==================================\n";

return 0;

return t; }

4. Test the application. Here is an example:

This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $750 Enter the Interest Rate (%): 11.25 Enter the number of months: 8 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ================================== Estimate on loan ---------------------------------Principal: $750 Interest: 11.25% Period: 8 Months ================================== Press any key to continue...

5. Return to your programming environment 6. In the above program, the clerk was asked to provide the number of months for the period of the loan. Depending on the loan, one customer may want to specify the number of days necessary to pay the loan. Another customer may want to pay a loan over a number of years. To make this possible, we will allow the clerk to select the type of period for a loan. Change the Main.cpp file as follows:

#include <iostream> using namespace std; double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); int main() { double int int string a " << "customer will owe at the end of the lifetime of a

Principal, IntRate; TypeOfPeriod; Periods; PeriodName;

cout << "This program allows you to calculate the amount of money

loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = GetPrincipal(); IntRate = GetInterestRate(); GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } "if" // condition produces true, the "return 0" means the function // would be terminated. If the condition is false, the inside of // this "if" condition would not execute and the function would // continue. This means that, if the condition is false, then // the "else' is implied. Therefore, we don't have to write an // "else" condition: it is automatic. if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout cout cout cout cout cout << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nPrincipal: $" << Principal; "\nInterest: " << IntRate << "%"; "\nPeriod: " << Periods << PeriodName; // Since this "if" condition has a "return 0" line, if the

cout << "\n==================================\n"; return 0; } double GetPrincipal() {

double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; } void GetPeriod(int &TypeOfPeriod, int &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; } }

7. Test the application. Here is an example:

This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $1500

Enter the Interest Rate (%): 10.75 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 3 Enter the number of years: 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ================================== Estimate on loan ---------------------------------Principal: $1500 Interest: 10.75% Period: 2 Years ================================== Press any key to continue...

8. Test the program again, making a different selection for the period. Here is an example:

This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $650 Enter the Interest Rate (%): 14.25 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years Your Choice: 8 Bad Selection Press any key to stop...

9. Return to your programming environment 10. Create a new unit and save it as Loan 11. In the Loan.h file, create the following namespace and function:

#ifndef LoanH #define LoanH

namespace Finance {

double InterestAmount(double P, double r, double t); }

#endif

12. In the Loan.cpp file, implement the function as follows:

#include "Loan.h"

namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } }

13. To prepare a test of the function, change the Main.cpp as follows:

#include <iostream> #include "Loan.h" using namespace std;

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods);

int main() {

double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period = GetPrincipal(); = GetInterestRate(); = GetPeriod(TypeOfPeriod, Periods);

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days";

} else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; }

cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\n==================================\n";

return 0; }

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

double GetInterestRate() { double r;

cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return Periods / 360; } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods;

return Periods / 12; } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return Periods; } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } }

14. Test the program. Here is an example:

This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $650 Enter the Interest Rate (%): 10.25 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years

Your Choice: 1 Enter the number of days: 120 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

================================== Estimate on loan ---------------------------------Principal: $650 Interest: Period: 10.25% 120 Days

-------------------------------Interest paid on Loan: $22.2083 ==================================

Press any key to continue...

15. Return to your programming environment Declaring a Pointer to Function A pointer to a function is a function that is declared as a pointer. Its name by itself is considered a variable. As such, and unlike a regular variable, the name of this function can be assigned a regular function. This allows the function to be passed as argument. The function itself is not implemented but its name is used as a programmer type-defined object. The reason a function can be passed as argument is because the name of a function is itself a constant pointer. The basic syntax to declare a pointer to a function is:
DataType (*FunctionName)();

The DataType can be any of the data types we have used so far and objects we will learn in future lessons. The FunctionName must be a valid name for a function. The name of the function must be preceded by an asterisk operator. To actually make this declaration a pointer to a function, the asterisk and the name of the pointer must be included between parentheses. If you omit the parentheses, the compiler would think that you are declaring a function that would return a pointer, which changes everything. Because this is a pointer, you must use parentheses, required for every function declared. If this

function will not take any argument, you can leave the parentheses empty or type void. Based on this, you can declare a pointer to a function as follows:
#include <iostream> using namespace std;

int main() { void (*SomethingToDo)(void);

return 0; }

After declaring a pointer to a function, keep in mind that this declaration only creates a pointer, not an actual function. In order to use it, you must define the actual function that would carry the assignment the function is supposed to perform. That function must have the same return type and the same (number of) argument(s), if any. For example, the above declared pointer to function is of type void and it does not take any argument. you can define a function as follows:
void MovieQuote() { cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << "\tFrom \"Disorganized Crime\"\n"; }

With such an associated function defined, you can assign it to the name of the pointer to function as follows
SomethingTodo = MovieQuote;

This assignment gives life to the function declared as pointer. The function can then be called as if it had actually been defined. Here is an example:
#include <iostream> using namespace std;

void MovieQuote()

{ cout << "We went through a lot of trouble because of you\n"; cout << "You owe us\n"; cout << " } From \"Disorganized Crime\"\n";

int main() { void (*SomethingToDo)();

// Assign the MovieQuote() function to the pointer to function SomethingToDo = MovieQuote;

// Call the pointer to function as if it had been defined already SomethingToDo();

return 0; }

This would produce:


We went through a lot of trouble because of you You owe us From "Disorganized Crime"

You can also type the keyword between the return type and the opening parenthesis. You can also declare a pointer to function for a function that returns a value. Remember that both functions must return the same type of value (they must have the same signature). Here is an example:
#include <iostream> using namespace std;

int Addition()

{ int a = 16, b = 442; return a + b; }

int main() { int (*SomeNumber)();

// Assign the MovieQuote() function to the pointer to function SomeNumber = Addition;

// Call the pointer to function as if it had been defined already cout << "The number is " << SomeNumber();

return 0; }

If you want to use a function that takes arguments, when declaring the pointer to function, provide the return type and an optional name for each argument. Here is an example:
int (*SomeNumber)(int x, int y);

When defining the associated function, besides returning the same type of value, make sure that the function takes the same number and type(s) of arguments. Here is an example:
#include <iostream> using namespace std;

int Addition(int a, int b) { return a + b; }

int main() { int (*SomeNumber)(int x, int y); int x = 128, y = 5055;

// Assign the MovieQuote() function to the pointer to function SomeNumber = Addition;

// Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << SomeNumber(x, y);

return 0; }

You can also create a programmer-defined type as a pointer to function. Here is the syntax to use:
typedef (*TypeName)(Arguments);

The typedef keyword must be used. The TypeName and its asterisk must be enclosed in parentheses. The name must follow the rules applied to objects so far. The TypeName must be followed by parentheses. If the pointer to function will take arguments, provide its type or their types between parentheses. Otherwise, you can leave the parentheses empty (but you must provide the parentheses). After creating such a custom type, the name of the type would be used as an alias to a pointer to function. Consequently, it can be used to declare a pointer to function. Here is an example:
#include <iostream> using namespace std;

int Addition(int a, int b) { return a + b;

int main() { // Creating a programmer-defined type typedef int (*AddTwoIntegers)(int x, int y); // Now, the AddsTwoIntegers name is a pointer to function // that can take two integers. It can be used for a declaration

AddTwoIntegers TwoNumbers; int x = 128, y = 5055;

TwoNumbers = Addition;

// Call the pointer to function as if it had been defined already cout << x << " + " << y << " = " << TwoNumbers(x, y);

return 0; }

This would produce:


128 + 5055 = 5183 Press any key to continue...

Practical Learning: Using a Pointer to Function 1. To declare and use a pointer to function, change the Main.cpp file as follows:

#include <iostream> using namespace std;

#include "Loan.h"

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; }

int main() { double (*AddValues)(double R, double T);

double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate = GetPrincipal(); = GetInterestRate();

Period AddValues

= GetPeriod(TypeOfPeriod, Periods); = Addition;

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = AddValues(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; }

cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n"; cout << "\n==================================";

cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount;

cout << "\n==================================\n";

return 0; }

. . . No Change

2. Test the program. Here is an example:

This program allows you to calculate the amount of money a customer will owe at the end of the lifetime of a loan

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the Principal: $1500 Enter the Interest Rate (%): 12.55 How do you want to enter the length of time? 1 - In Days 2 - In Months 3 - In Years

Your Choice: 3 Enter the number of years: 2 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

================================== Estimate on loan ---------------------------------Principal: $1500 Interest: Period: 12.55% 2 Years

-------------------------------Interest paid on Loan: $376.5 Total Amount Paid: $1876.5

==================================

Press any key to continue...

3. Return to your programming environment 4. To create a programmer-define type based on the AddValues pointer to function name, click the Loan.h tab and create the type as follows:

#ifndef LoanH #define LoanH

namespace Finance { typedef double (*Add)(double R, double T);

double InterestAmount(double P, double r, double t);

#endif

5. To declare and use a variable of the new defined type, change the Main.cpp file as follows:

#include <iostream>

using namespace std;

#include "Loan.h"

double GetPrincipal(); double GetInterestRate(); double GetPeriod(int &PeriodType, double &NumberOfPeriods); double Addition(double Value1, double Value2) { return Value1 + Value2; }

int main() { Finance::Add Plus; double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods;

string PeriodName;

cout << "This program allows you to calculate the amount of money a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period Plus = GetPrincipal(); = GetInterestRate(); = GetPeriod(TypeOfPeriod, Periods); = TotalAmount;

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

. . . No Change

return 0;

. . .

6. Test the application and return to your programming environment 7. To expand the Loan unit, we will add other types to perform all four arithmetic operations used to assist the functions that will be called to perform the calculations. In the Loan.h file, create the following programmer-defined types:

#ifndef LoanH #define LoanH

namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second);

double InterestAmount(double P, double r, double t); }

#endif

8. Create a header file and save it as Main.h (make sure you include the .h extension) 9. To make the Main.cpp file less crowded, in the Main.h file, define the following accessory functions in their own namespace:

#if !defined MainH #define MainH

#include <iostream>

using namespace std; namespace Accessories { // Accessory Functions

// This function adds two values double Addition(double Value1, double Value2) { return Value1 + Value2; }

// This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; }

// This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; }

// This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second

double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories

namespace LoanProcessing {

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

double GetInterestRate() { double r;

cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n";

return 0.00; } }

#endif

// MainH

10. To prepare a test for the new changes, change the Main.cpp file as follows:

#include <iostream> using namespace std;

#include "Main.h" #include "Loan.h"

int main() { // Declare a variable of type Add, defined in the Finance namespace Finance::Add Plus;

double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "This program allows you to calculate the amount of money

a " << "customer will owe at the end of the lifetime of a loan\n";

cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal IntRate Period Periods); Plus = LoanProcessing::GetPrincipal(); = LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod, = Accessories::Addition;

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); double Amount = Plus(Principal, InterestAmount);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return 0; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months";

} else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n";

cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\nTotal Amount Paid: $" << Amount;

cout << "\n==================================\n";

return 0; }

11. Test the application and return to your programming environment 12. Save All A Pointer to a Function as Argument your programming environmentUsing pointer to functions, a function can be passed as argument to another function. The function must be passed as a pointer. The argument is declared in a complete format as if you were declaring a function. Here is an example of a function that is passed a function as argument.
double Circumference(double (*FDiam)(double R))

This Circumference() function takes one argument. The argument itself is a pointer to function. This argument itself takes a double-precision number as argument and it returns a double-precision value. The Circumference() function returns a double-precision number. It is important to know that the pointer to function that is passed as argument is declared completely, in this case as
double (*FDiam)(double R)

Although the FDiam declaration is accompanied by an argument, in this case R, this argument allows the compiler to know that FDiam takes an argument. This argument actually will not be processed by the Circumference() function when the Circumference() function is defined because the R argument does not belong to the Circumference() function. When calling the Circumference() function, you will use the FDiam argument as a variable in its own right, using its name, as in
Circumference(Diameter)

When defining the Circumference() function, you must process the pointer to function that it takes as argument. If this argument is an alias to a function that returns a value, you can call it and pass it the argument as we studied in the last section. If you want to involve the FDiam argument in any operation, you can declare a local variable to the Circumference() function. If the FDiam argument must be involved in an operation that involves a value external to the Circumference() function, you must pass that type of value as argument to the Circumference() function, unless you are using a global variable (we will study global variables when we review the issue of scopes). This means that, in most circumstances, the pointer to function passed as argument may be accompanied by at least one other argument. For example, if you want to use the FDiam as a diameter value to calculate the circumference (Circumference = Diameter * PI), you may have to declare it with an argument for the radius. It would be declared as follows:
double Circumference(double (*FDiam)(double R), double Rad);

The function can then be implemented as follows:


double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad);

return Circf * PI;

Remember that, when declaring a function, the compiler does not care about the name(s) of the argument(s). If the function takes any, what the compiler cares about are the return type of the function, its name, and the type(s) of its argument(s), if any. Therefore, the above function could as well be declared as follows:
double Circumference(double (*)(double R), double);

This indicates that the Circumference() function takes two arguments whose names are not known. The first argument is a pointer to a function that takes one double-precision number as argument and returns a double. The second argument of the Circumference() function is also a double-precision number. The Circumference() function returns a double-precision number. This is what the program at this time would look like:
#include <iostream> using namespace std;

double Diameter(double); double Circumference(double (*D)(double R), double r);

int main() { double Radius;

Radius = 25.52;

cout << "Cylinder Summary"; cout << "\nRadius: " << Radius;

cout << "\nCircumference = " << Circumference(Diameter, Radius) << endl;

return 0; }

double Diameter(double Rad) { return Rad * 2; }

double Circumference(double (*FDiam)(double R), double Rad) { double Circf; const double PI = 3.14159; Circf = (*FDiam)(Rad);

return Circf * PI; }

This would produce:


Cylinder Summary Radius: 25.52

Circumference = 160.347

Press any key to continue...

To simplify the declaration of a pointer to function, we saw that you can create a programmer-defined type using the typedef keyword. This can also help when passing a function as argument. Here is an example:
typedef double (*FDiam)(double R); double Circumference(FDiam, double);

When creating such a programmer-defined type, remember that you must give a name to the alias, in this case FDiam. After this creation, FDiam is an alias to a pointer to function of a double-precision type and which takes one double-precision number as argument.

Remember, as we learned when studying functions that return a value, that the item on the right side of the return keyword can be a value or a complete expression. Therefore, you can simplify the implementation of the Circumference() function as follows:
double Circumference(double (*FDiam)(double R), double Rad) { const double PI = 3.14159; return (*FDiam)(Rad) * PI; }

Practical Learning: Passing a Function as Argument 1. To declare a function that takes another function as argument, in the Loan.h file, declare the following function:

#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); double Rate(double (*AP)(double A, double P), double a, double p, double t); } #endif

2. In the Loan.cpp, implement the function as follows:

#include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; }

double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100; } }

3. To provide a function used to get the future value of a loan, in the Main.h file, define a GetAmount() function as follows:

#if !defined MainH #define MainH . . . No Change namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } . . . No Change #endif // MainH

4. To call the new function, change the Main.cpp file as follows:

#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; int main() { double int double string

Principal, Amount, IntRate, Period, InterestAmount; TypeOfPeriod; Periods; PeriodName;

cout << "This program allows you to perform estimations on loans\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); IntRate = Finance::Rate(Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop..."; return 0; } if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nPrincipal: $" << Principal; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nInterest on Loan: " << IntRate << "%"; "\n==================================\n";

return 0;

5. Test the application. Here is an example:

This program allows you to perform estimations on loans %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Loan Processing Enter the future value: $4500 Enter the Principal: $3000 How do you want to enter the length of time?

1 - In Days 2 - In Months 3 - In Years Your Choice: 3 Enter the number of years: 3 ================================== Estimate on loan ---------------------------------Future Value: $4500 Principal: $3000 Period: 3 Years -------------------------------Interest on Loan: 16.6667% ================================== Press any key to continue...

6. To provide more options to the user and make the program more complete, you can create a menu, allowing the clerk to select the type of calculation. A customer may want to know how much time would be a better length of time to pay a loan. The customer may want to find the differences among the time (period), the rate of interest, the monthly payment the customer can afford, the length of time (the number of days, months or years the customer wants to pay the loan. To allow the user to select the type of calculation to perform, in the Main.h file, define the following functions:

#if !defined MainH #define MainH

#include <iostream>

#include "Loan.h"

using namespace std; namespace Accessories { // Accessory Functions

// This function adds two values double Addition(double Value1, double Value2)

{ return Value1 + Value2; }

// This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; }

// This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; }

// This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } } // namespace Accessories

namespace LoanProcessing {

double GetAmount() { double A;

cout << "Enter the future value: $"; cin >> A; return A; }

double GetPrincipal() { double P;

cout << "Enter the Principal: $"; cin >> P; return P; }

double GetInterestRate() { double r;

cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod;

if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n";

return 0.00; } }

int SelectCalculationType() { int Answer;

cout << "What kind of value do you want to estimate?"; cout << "\n1 - Calculate (only) the interest paid on the loan"; cout << "\n2 - Estimate the future value of the entire loan"; cout << "\nYour choice: "; cin >> Answer;

return Answer; }

void ProcessInterestAmount() { double Principal, IntRate, Period, InterestAmount; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal();

IntRate Period Periods);

= LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod,

InterestAmount = Finance::InterestAmount(Principal, IntRate, Period);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n";

cout << "\n==================================";

cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: cout << "\nPeriod: " << IntRate << "%"; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; cout << "\n==================================\n"; }

void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period; int TypeOfPeriod;

double Periods; string PeriodName;

cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount();

Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);

IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period);

if( TypeOfPeriod == 0 ) {

// Since the user made a bad selection, stop the program here cout << "Press any key to stop...";

return; }

if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; }

cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: cout << "\nPeriod: $" << Principal; " << Periods << PeriodName;

cout << "\n--------------------------------"; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n==================================\n";

#endif

// MainH

7. To test the new version of the program, change the Main.cpp file as follows:

#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessRateOfInterest(); break; default: cout << "\nInvalid Selection\n"; } return 0; }

8. Test the application and return to your programming environment 9. To allow the clerk to process other types of calculations, in the Loan.h file, declare the following functions:

#ifndef LoanH #define LoanH namespace Finance { typedef double (*Add)(double R, double T); typedef double (*Subtract)(double First, double Second); typedef double (*Multiply)(double First, double Second); typedef double (*Divide)(double First, double Second); double InterestAmount(double P, double r, double t); double Rate(double (*AP)(double A, double P), double a, double p, double t); double TotalLoanAmount(double P, double r, double t); double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A); double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r); double Period(double (*AP)(double A, double P), double a, double p, double r); } #endif

10. In the Loan.cpp file, implement the functions:

#include "Loan.h" #pragma package(smart_init) namespace Finance { // Interest = Principal * rate * time in years double InterestAmount(double P, double r, double t) { return P * (r / 100) * t; } // Amount - Principal // Interest rate of a loan = -------------------// Principal * Period double Rate(double (*AP)(double A, double P), double a, double p, double t) { double AMinusP = (*AP)(a, p); double Pt = p * t; return (AMinusP / Pt) * 100;

} // Amount = Principal(1 + Rate * Interest) double TotalLoanAmount(double P, double r, double t) { return P * (1 + ((r / 100) * t)); } // Amount // Principal = -----------------// 1 + Rate * Period double PrincipalAmount(double (*RT)(double a, double b), double R, double T, double A) { double RateOnTime = (*RT)(R/100, T); return A / (1 + RateOnTime); } // Amount - Principal // Interest rate of a loan = -------------------// Principal * Rate // The following function provides a very simplistic way to calculate the // length of time of a loan. In fact, there is no checking on the // periodic value (whether the value is in days, quarters, months, or // years, and there is no algorithm to check the value of the time double Period(double (*AP)(double A, double P), double (*PR)(double P, double R), double a, double p, double r) { double AMinusP = (*AP)(a, p); double PTimesR = (*PR)(p, r / 100); return AMinusP / PTimesR; } }

11. To expand the menu, change the Main.h file accordingly:

#if !defined MainH #define MainH #include <iostream> #include "Loan.h" using namespace std; namespace Accessories { // Accessory Functions // This function adds two values double Addition(double Value1, double Value2) {

return Value1 + Value2; } // This function takes two arguments. // It subtracts the second from the first double Subtraction(double Value1, double Value2) { return Value1 - Value2; } // This function multiplies two numbers double Multiplication(double Value1, double Value2) { return Value1 * Value2; } // This function takes two arguments // If the second argument is 0, the function returns 0 // Otherwise, the first argument is divided by the second double Division(double Numerator, double Denominator) { if( Denominator == 0 ) return 0; // else is implied return Numerator / Denominator; } // namespace Accessories

namespace LoanProcessing { double GetAmount() { double A; cout << "Enter the future value: $"; cin >> A; return A; } double GetPrincipal() { double P; cout << "Enter the Principal: $"; cin >> P; return P; } double GetInterestRate() { double r; cout << "Enter the Interest Rate (%): "; cin >> r; return r; }

double GetPeriod(int &TypeOfPeriod, double &Periods) { cout << "How do you want to enter the length of time?"; cout << "\n1 - In Days"; cout << "\n2 - In Months"; cout << "\n3 - In Years"; cout << "\nYour Choice: "; cin >> TypeOfPeriod; if( TypeOfPeriod == 1 ) { cout << "Enter the number of days: "; cin >> Periods; return static_cast<double>(Periods / 360); } else if( TypeOfPeriod == 2 ) { cout << "Enter the number of months: "; cin >> Periods; return static_cast<double>(Periods / 12); } else if( TypeOfPeriod == 3 ) { cout << "Enter the number of years: "; cin >> Periods; return static_cast<double>(Periods); } else { TypeOfPeriod = 0; // The user made an invalid selection. So, we will give up cout << "\nBad Selection\n"; return 0.00; } } int SelectCalculationType() { int Answer; cout << "What kind of value do you want to estimate?"; cout << "\n1 - Calculate (only) the interest paid on the loan"; cout << "\n2 - Calculate the total amount owed on a loan"; cout << "\n3 - Estimate the interest rate applied on a loan"; cout << "\n4 - Find the amount given as loan"; cout << "\n5 - Find the approximate length of time of a loan"; cout << "\nYour choice: "; cin >> Answer; return Answer; } void ProcessInterestAmount(bool GetTotalAmount = false) { double Principal, Amount, IntRate, Period, InterestAmount; int TypeOfPeriod; double Periods; string PeriodName;

cout << "\n====================================================="; cout << "\nWe will calculate the interest amount payed on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } InterestAmount = Finance::InterestAmount(Principal, IntRate, Period); Amount = Finance::TotalLoanAmount(Principal, IntRate, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout << "\n"; cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nPrincipal: $" << Principal; cout << "\nInterest: " << IntRate << "%"; cout << "\nPeriod: " << Periods << PeriodName; cout << "\n--------------------------------"; cout << "\nInterest paid on Loan: $" << InterestAmount; if( GetTotalAmount == true ) cout << "\nTotal Amount Paid: $" << Amount; cout << "\n==================================\n"; } void ProcessRateOfInterest() { double Principal, Amount, IntRate, Period;

int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the interest rate applied on a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); Principal = LoanProcessing::GetPrincipal(); Period = LoanProcessing::GetPeriod(TypeOfPeriod, Periods); if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } IntRate = Finance::Rate(Accessories::Subtraction, Amount, Principal, Period); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } void ProcessPrincipal() { double Principal, Amount, IntRate, Period; int TypeOfPeriod; double Periods; string PeriodName; << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nPrincipal: $" << Principal; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nInterest on Loan: " << IntRate << "%"; "\n==================================\n";

cout << cout << cout << cout << Amount IntRate Period

"\n=================================================="; "\nWe will calculate the principal value of the loan"; "\n=================================================="; "\nLoan Processing\n"; = LoanProcessing::GetAmount(); = LoanProcessing::GetInterestRate(); = LoanProcessing::GetPeriod(TypeOfPeriod, Periods);

if( TypeOfPeriod == 0 ) { // Since the user made a bad selection, get out of the function cout << "\nThe program will stop"; return; } Principal = Finance::PrincipalAmount(Accessories::Multiplication, IntRate, Period, Amount); if( TypeOfPeriod == 1 ) { PeriodName = " Days"; } else if( TypeOfPeriod == 2 ) { PeriodName = " Months"; } else if( TypeOfPeriod == 3 ) { PeriodName = " Years"; } cout cout cout cout cout cout cout cout cout } void ProcessPeriod() { double Principal, Amount, IntRate, TimeSpan; int TypeOfPeriod; double Periods; string PeriodName; cout << "\n====================================================="; cout << "\nWe will calculate the amount of time to pay a loan\n"; cout << "\n====================================================="; cout << "\nLoan Processing\n"; Amount = LoanProcessing::GetAmount(); << << << << << << << << << "\n=================================="; "\nEstimate on loan"; "\n----------------------------------"; "\nFuture Value: $" << Amount; "\nInterest on Loan: " << IntRate << "%"; "\nPeriod: " << Periods << PeriodName; "\n--------------------------------"; "\nPrincipal: $" << Principal; "\n==================================\n";

Principal = LoanProcessing::GetPrincipal(); IntRate = LoanProcessing::GetInterestRate(); TimeSpan = Finance::Period(Accessories::Subtraction, Accessories::Multiplication, Amount, Principal, IntRate); cout << "\n=================================="; cout << "\nEstimate on loan"; cout << "\n----------------------------------"; cout << "\nFuture Value: $" << Amount; cout << "\nPrincipal: $" << Principal; cout << "\nInterest on Loan: " << IntRate << "%"; cout << "\n--------------------------------"; cout << "\nPeriod: " << TimeSpan * 12 << " Months"; cout << "\n==================================\n"; } } #endif // MainH

12. To prepare for a test, in the Main.cpp, add the new options in the main() function:

#include <iostream> #include "Main.h" #include "Loan.h" using namespace std; using namespace Accessories; using namespace LoanProcessing; int main() { int TypeOfCalculation; cout << "This program allows you to perform estimations on loans\n"; TypeOfCalculation = SelectCalculationType(); switch(TypeOfCalculation) { case 1: ProcessInterestAmount(); break; case 2: ProcessInterestAmount(true); break; case 3: ProcessRateOfInterest(); break; case 4: ProcessPrincipal();

break; case 5: ProcessPeriod(); break; default: cout << "\nInvalid Selection\n"; } return 0; }

13. Test the application. Here is an example:

This program allows you to perform estimations on loans What kind of value do you want to estimate? 1 - Calculate (only) the interest paid on the loan 2 - Calculate the total amount owed on a loan 3 - Estimate the interest rate applied on a loan 4 - Find the amount given as loan 5 - Find the approximate length of time of a loan Your choice: 5 ===================================================== We will calculate the amount of time to pay a loan ===================================================== Loan Processing Enter the future value: $824 Enter the Principal: $800 Enter the Interest Rate (%): 9 ================================== Estimate on loan ---------------------------------Future Value: $824 Principal: $800 Interest on Loan: 9% -------------------------------Period: 4 Months ================================== Press any key to continue...

14. Return to your programming environment and save everything An Array of (Pointers to) Functions To further refine the call to a group of functions that perform the same kind of task, you can declare an array of pointers to a type of function. Before creating an array of pointers to function, you must first know or have the functions you would be referring to. These functions must have a similar signature. This means that they must return the same type of value, they must have the same number

of arguments and they must have the same type(s) of argument(s). Here are examples of such functions:
double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; }

To declare an array of pointers to function, you can first define an alias to the variable. This is an example:
typedef double (*Measure)(double R);

After this definition, as we learned already, Measure is an alias to a function that takes a double type of variable and returns a double value. Using this name, you can declare an array of functions. The members of the array are names of the functions that would compose the array. Here is an example:
Measure Calc[] = { Diameter, Circumference, Area };

You can initialize each member using its index and calling the corresponding function. This can be done as follows:
#include <iostream> using namespace std; const double PI = 3.14159; double Diameter(double Radius) { return Radius * 2; } double Circumference(double Radius) { return Diameter(Radius) * PI; } double Area(double Radius) { return Radius * Radius * PI; } int main() { typedef double (*Measure)(double R);

double R = 12.55; Measure Calc[] = { Diameter, Circumference, Area }; double D = Calc[0](R); double C = Calc[1](R); double A = Calc[2](R); cout << "Circle Characteristics"; cout << "\nDiameter: " << D; cout << "\nCircumference: " << C; cout << "\nArea: " << A << endl; return 0; }

This would produce:


Circle Characteristics Diameter: 25.1 Circumference: 78.8539 Area: 494.808 Press any key to continue...

Practical Learning: Using an Array of Functions 1. 2. 3. 4. Create a new project using the Console Wizard To save the project, create a new folder called Multiple Choice1 Save the unit as Exercise and save the project as MCQ1 To experiment with an array of functions, change the Exercise.cpp file as follows:

#include <iostream> using namespace std; typedef char (*Question)(); enum TMCQuestion { One, Two, Three, Four, Five }; char Sequence() { char Answer; cout << "Which sequence of numbers does not appear to follow " << "a recognizable order?"; cout << "\n(a) 3 9 27 33"; cout << "\n(b) 3 6 9 12"; cout << "\n(c) 2 4 6 8"; cout << "\n(d) 102 204 408 816"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char Expression() { char Response; cout << "Select the best expression to complete the empty space";

cout << "\nWhen ... drugs to a business address, traffickers often " << "omit a recipient name"; cout << "\n(a) to send"; cout << "\n(b) senders"; cout << "\n(c) sending"; cout << "\n(d) dealing"; cout << "\nAnswer: "; cin >> Response; return Response; } char Sentence() { char Answer; cout << "Even ... there are 76,000 lawyers in that city, it is still " << "a small community"; cout << "\n(a) although"; cout << "\n(b) though"; cout << "\n(c) for"; cout << "\n(d) since"; cout << "\nAnswer: "; cin >> Answer; return Answer; } char WrongWord() { char Wrong; cout << "Select the wrong word that would complete the sentence"; cout << "\nFor this type of business, revenue gains are ..."; cout << "\n(a) limited"; cout << "\n(b) scarce"; cout << "\n(c) limitless"; cout << "\n(d) claiming"; cout << "\nAnswer: "; cin >> Wrong; return Wrong; } char Right() { char Sentence; cout << "Select the right sentence"; cout << "\n(a) The company is expecting to reducing inventory," << "\n control cost, and efficiency improvement."; cout << "\n(b) The company expects to reduce inventory," << "\n control cost, and improve efficiency."; cout << "\n(c) The company expects to reduce inventory," << "\n control cost, and improving efficiency."; cout << "\n(d) The company is expecting to reducing inventory," << "\n controlling cost, and efficiency improvement."; cout << "\nAnswer: "; cin >> Sentence; return Sentence; }

void ValidateAnswer(const int QstNbr, const char Ans); int main() { const int NumberOfQuestions = 5; char ValidAnswer; char Answer[NumberOfQuestions]; Question MCQ[] = { Sequence, Expression, Sentence, WrongWord, Right}; for(int i = 0; i < NumberOfQuestions; i++) { cout << "Question " << i + 1 << endl; Answer[i] = MCQ[i](); ValidateAnswer(i+1, Answer[i]); cout << "\n\nPress any key to continue..."; clrscr(); } return 0; } void ValidateAnswer(const int QstNbr, const char Ans) { switch(QstNbr) { case 1: if(Ans == 'a' || Ans == 'A') cout << "Right Answer"; else { cout << "Wrong Answer - The right answer was 'a'"; cout << "\n(a) Starting at 3, 3*3=9 and 3*9=27"; cout << "\n There is no obvious way to determine 33"; } break; case 2: if(Ans == 'c' || Ans == 'C') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'c'"; break; case 3: if(Ans == 'b' || Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'b'"; break; case 4: if(Ans == 'd' || Ans == 'D')

cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'd'"; break; case 5: if(Ans == 'b' || Ans == 'B') cout << "Right answer"; else cout << "Wrong Answer - The right answer was 'b'"; break; default: cout << "Invalid Answer"; } }

5. Test the application 6. Return to your programming environment and save all

Strings Arrays of Characters Re-Introduction to Characters In our second lesson, we had a brief introduction to arrays of characters and strings. So far, we have avoided using them whenever we did not have to. As it happens, strings are the most used items of computers. In fact, anything the user types is a string. It is up to you to convert it to another, appropriate, type of your choice. This is because calculations cannot be performed on strings. On the other hand, strings can be a little complex, which is why we wanted to first know how to use the other types and feel enough comfortable with them. Consider a name such as James. This is made of 5 letters, namely J, a, m, e, and s. Such letters, called characters, can be created and initialized as follows:
char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

To display these characters as a group, you can use the following:


cout << "The name is " << L1 << L2 << L3 << L4 << L5;

Here is such a program:


#include <iostream> using namespace std;

int main() { char L1 = 'J', L2 = 'a', L3 = 'm', L4 = 'e', L5 = 's';

cout << "The name is " << L1 << L2 << L3 << L4 << L5;

return 0; }

This would produce:


The name is James

Declaring and Initializing an Array of Characters When studying arrays, we were listing the numeric members of the array between curly bracket. Here is an example:
int Number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Because a character is initialized by including it in single-quotes, when creating an array of characters, to initialize it, you must also include each letter accordingly. A name such as James can be initialized as follows:
char Name[6] = { 'J', 'a', 'm', 'e', 's' };

As done with other arrays, each member of this array of characters can be accessed using its index. Here is an example:
#include <iostream> using namespace std;

int main() { char Name[6] = { 'J', 'a', 'm', 'e', 's' };

cout << "The name is " << Name[0] << Name[1] << Name[2]

<< Name[3] << Name[4];

return 0; }

The C/C++ provides another alternative. It allows you to declare and initialize the array as a whole. To do this, include the name in double-quotes. With this technique, the curly brackets that delimit an array are not necessary anymore. Here is an example:
char Name[12] = "James";

With this technique, the item between the double-quotes is called a string. It is also referred to as the value of the string or the value of the variable. When declaring and initializing an array of characters, the compiler does not need to know the number of characters of the string. In fact, you can let the compiler figure it out. Therefore, you can leave the square brackets empty:
char Name[] = "James";

After declaring such an array, the compiler would count the number of characters of the variable, add one more variable to it and allocate enough space for the variable. The character added is called the null-terminated character and it is represented as \0. Therefore, a string such as James would be stored as follows: J a m e s \0

This something you will need to remember regularly.


Color = Black Country = Swaziland

Streaming an Array of Characters Like any other variable, before using a string, you must first declare it, which is done by type the char keyword, followed by the name of the variable, followed by square brackets. When declaring the variable, if/since you do not know the number of characters needed for the string, you must still provide an estimate number. You can provide a value large enough to accommodate the maximum number of characters that would be necessary for the variable. For a person's name, this could be 20. For the title of a book or a web page, this could be longer. Here are examples:
char Name[20];

char BookTitle[40]; char WebReference[80]; char WeekDay[4];

To request the value of an array of characters, use the cin extractor just like you would proceed with any other variable, without the square bracket. Here is an example:
char WeekDay[12];

cout << "Enter today's name: "; cin >> WeekDay;

To display the value of an array of characters, use the cout extractor as we have used it with all other variables, without the square brackets. Here is an example:
#include <iostream> using namespace std;

int main() { char WeekDay[12]; char EndMe[] = "\n";

cout << "Enter today's name: "; cin >> WeekDay;

cout << "Today is " << WeekDay;

cout << EndMe;

return 0; }

Here is an example of running the program:


Enter today's name: Thursday Today is Thursday

Multidimensional Arrays of Characters C/C++ treats arrays of characters differently than it does the other arrays. For example, we have learned to declare a two-dimensional array of integers as follows:
int Number[2][6] = { { 31, 28, 31, 30, 31, 30 }, { 31, 31, 30, 31, 30, 31 } };

This variable is in fact two arrays and each array contains 6 integers. For a string, if you want to declare a two-dimension array of characters, the first dimension specifies the number of string in the variable. The second dimension specifies the number of characters that each string can hold. Here is an example:
char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

In this case, the StudentName variable is an array of 4 strings and each string can have a maximum of 9 characters (+1 for the null-terminated character). To locate a string on this variable, type the name of the array followed by its index, which is the index of the column. This means that the first string of the StudentName array can be accessed with StudentName[0]. The second would be StudentName[1], etc. This allows you to display each string on the cout extractor:
#include <iostream> using namespace std;

int main() { char StudentName[4][10] = { "Hermine", "Paul", "Gertrude", "Leon" };

cout << "Student Names"; cout << "\nStudent 1: " << StudentName[0]; cout << "\nStudent 2: " << StudentName[1];

cout << "\nStudent 3: " << StudentName[2]; cout << "\nStudent 4: " << StudentName[3];

return 0; }

This would produce:


Student Names Student 1: Hermine Student 2: Paul Student 3: Gertrude Student 4: Leon

When declaring and initializing such an array, the compiler does not need to know the number of strings in the array; it can figure it out on its own. Therefore, you can leave the first pair square brackets empty. If you are only declaring the array but cannot initialize, then you must specify both dimensions. To request the values of the array, once again, locate each member using its index. Here is an example:
Enther the first name of each player Student 1: Walter Student 2: Guy Student 3: Celestin Student 4: Maurand Student 5: Phillipe

Student Names Student 1: Walter Student 2: Guy Student 3: Celestin

Student 4: Maurand Student 5: Phillipe

There are two alternatives to solve this problem: you can use the getline() function from the basic_string library or you can use the gets() function from the C language. Pointers and Arrays of Characters Declaring a Pointer to Characters Earlier, we declared an array as follows:
char EndMe[] = "";

The name of the variable is a pointer to the beginning of the array. For this reason, the name of the reason is sufficient to locate its value. Since in this case we do not specify the number of characters in the array, we can also just use a pointer to the array as the beginning of the array. The array can therefore be declared as follows:
char *EndMe = "";

Once again, to display the value of such an array, simply call its name on the cout extractor:
#include <iostream> using namespace std;

int main() { char *EndMe = "";

cout << EndMe;

return 0; }

To request the value of an array of characters from the user, you can declare a pointer to char and initialize it with an estimate number of characters using the new operator. Here is an example:
#include <iostream>

using namespace std;

int main() { char *StudentName = new char[20];

cout << "Enter Sudent First Name: "; cin >> StudentName;

cout << "\nStudent First Name: " << StudentName;

return 0; }

Here is an example of running the program:


Enter Sudent First Name: Charlotte

Student First Name: Charlotte

Declaring and Initializing an Array of Characters From our study and use of characters, we have seen that, to declare a character variable, we can use any C++ valid name. To initialize a character variable, type it between single-quotes. Here is an example:
char Answer = y;

To declare an array of characters, type the char keyword followed by the techniques we used to declare the other arrays. The syntax is:
char ArrayName[Dimension];

The char keyword lets the compiler know that you are declaring a variable of character type. The square brackets let the compiler know that you are declaring an array. The name of the array follows the same rules and suggestions we have used for the other variables. Once again, the dimension of the

array could be an approximation of the number of characters you anticipate. To initialize an array of characters, you use the curly brackets. Each character must be enclosed in single-quotes. If you know the characters you will be using to initialize the array, you should omit specifying the dimension. Here is an example:
char Color[] = { 'B', 'l', 'a', 'c', 'k' };

Another technique used to initialize an array of characters is to type the group of characters between double-quotes. Since you know the array, let the compiler figure out its dimension. Here is an example:
char Country[] = "Swaziland";

Any of these two techniques would allow you to display the string using the cout operator. The compiler already knows the dimension and the contents of the array:
#include <iostream> using namespace std;

int main() { char Color[] = { 'B', 'l', 'a', 'c', 'k' }; char Country[] = "Swaziland";

cout << "Color = " << Color << endl; cout << "Country = " << Country;

return 0; }

This would produce:


Color = Black Country = Swaziland

Requesting an Array of Characters Instead of initializing an array, sometimes you will have to wait until the program is running, to assign a value to the array. First, you must declare the array, specifying an approximate dimension. To request the value of an array of characters, use the cin operator, specifying only the name of the

array. Here is an example:


#include <iostream> using namespace std;

int main() { char FirstName[20]; char MI; char LastName[20];

cout << "The following pieces of information are need" << "to complete your application\n"; cout << "First Name: "; cin >> FirstName; cout << "Middle Initial: "; cin >> MI; cout << "Last Name: "; cin >> LastName;

cout << "\nMember Information"; cout << "\nFull Name: " << FirstName << " " << MI << ". " << LastName;

return 0; }

Here is an example of running the program:


The following pieces of information are need to complete your application

First Name: Michael Middle Initial: J Last Name: Callhoun

Member Information Full Name: Michael J. Callhoun

If you use the normal cin operator above, the compiler expects the user to type a one-word string from the keyboard. If you want the user to type text that includes space, you should use the cin::getline() function. The syntax of the getline() function is:
cin.getline(ArrayName, Dimension, Delimiter=\n);

The array name is the one you used when declaring the array. The dimension is the same value you set when declaring the variable. The delimiter is an optional character that the user would type to specify the end of the string. By default, the compiler expects the user to press Enter to end the string. Logically, the following program illustrates the use of the cin::getline() function to request text strings from the user:
#include <iostream> using namespace std;

int main() { char Author[40]; char Title[40]; char Publisher[50];

cout << "Book Collection\n"; cout << "Author: "; cin.getline(Author, 40); cout << "Title: "; cin.getline(Title, 40); cout << "Publisher: "; cin.getline(Publisher, 50);

cout << "\nBook Information";

cout << "\nAuthor Name: " << Author << "\nBook Title: " << Title << "\nPublisher: " << Publisher;

return 0; }

Here is an example of running the program:


Book Collection Author: Elliot Mendelson Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill

Book Information Author Name: Elliot Mendelson Book Title: 3000 Solved Problems In Calculus Publisher: McGraw Hill

Arrays of Characters and Pointers Declaration of an Array of Characters We have learned to declare an array of characters using the square brackets and to initialize it using the assignment operator. By not specifying the dimension of the array, we are relying on the compiler to find out how many items the array has. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[] = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n";

return 0; }

As you can see for this example, to display the value of the Country variable, although it is an array, all the compiler needs is the name. How come? As it happens, when you create an array of characters, such as the Country variable above, the name of the array is the same as Country[0]. In other words, it represents the beginning of the space memory occupied by the variable. As we saw when studying pointers, this beginning of the space occupied by a variable is referred to as its address. Because the compiler knows this and is able to figure it out, C++ provides another solution. Instead of declaring the array with empty square brackets, since we are in fact referring to the address of the variable, we can declare it a pointer to char. Therefore, the above program can be written as follows:
#include <iostream> using namespace std;

int main() { char *Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n"; return 0; }

Both programs would produce the same result. There is something important to know about this new version. The asterisk on the name informs the compiler that it should consider the Country variable starting at its address and up. If you do not initialize the variable, the compiler would not complain as long it is now able to locate the variable. Based on this, you can initialize the variable when you are ready and not necessarily when you declare it. Keep in mind that this theory is valid only for an array of characters; for example the following program will not compile:
#include <iostream> using namespace std;

int main() { double *Value;

Value = 12.55;

cout << "Value = " << Value;

return 0; }

On the other hand, the following declaring of an array of characters and its later initialization is perfectly legal:
#include <iostream> using namespace std;

int main() { char *Country;

Country = "Republique d'Afrique du Sud";

cout << "Country Name: " << Country << "\n\n"; return 0; }

Dynamic Arrays of Characters A dynamic object is one whose memory is requested and used only when needed. Such objects are created using the new operator. In the same way, to dynamically create an array, you use the new operator. To do this, the variable must be declared a pointer to char, as done above. Then assign the new char expression that followed by a pair of square brackets. In the square brackets, specify the desired dimension of the array. An example would be:
char *Country = new char[20];

After declaring such a variable, you can assign it any value you want. Here is an example:
#include <iostream> using namespace std;

int main() { char *Country = new char[20];

Country = "Equatorial Guinea"; cout << "Country Name: " << Country;

cout << "\n\n"; return 0; }

Passing an Array of Characters Like other regular arrays, you can pass an array of characters to a function or you can return an array of characters from a function. To pass an array of characters to a function, when declaring and when defining the function, provide the name of the array followed by empty parentheses. When calling the function, provide only the name of the argument you are passing. Here is an example:
#include <iostream> using namespace std;

void ShowCountry(const char S[]) { cout << "Country Name: " << S << "\n\n"; }

int main() { char Country[] = "Republique d'Afrique du Sud";

ShowCountry(Country); return 0; }

Alternatively, as we have learned that you can also declare an array of characters using a pointer to

char, when declaring and when defining the array, you can provide the argument as a pointer to char. When calling the function, provide the argument of the function by specifying only the name of the argument:
#include <iostream> using namespace std;

void ShowCountry(const char *S) { cout << "Country Name: " << S << "\n\n"; }

int main() { char *Country = "Republique d'Afrique du Sud";

ShowCountry(Country);

return 0; }

Returning an array of Characters Just as you can pass an array of characters to a function, you can also return such an array from a function. To do this, the function must be declared and defined as a pointer to char. Here is an example:
char *GetFirstName();

When calling such a function, you are requesting its value and want to assign it to a variable, make sure that the variable is also declared as pointer to char. Here is an example:
#include <iostream> using namespace std;

char *GetFirstName() {

char *FName = new char[20];

cout << "Enter First Name: "; gets(FName);

return FName; }

int main() { char *FirstName;

FirstName = GetFirstName(); cout << "First Name: " << FirstName << "\n\n"; return 0; }

Multidimensional Arrays of Characters Double-Dimensional Arrays Declaration Once again, an array of characters is different from an array of other regular data types. Imagine you want to create various lists of countries. You would declare such an array as follows: char Country[3][8]; Unlike other data types, it is important to know what each dimension represents. This array initiates 3 lists of countries. Each country can have up to 8 letters. In other words, the first dimension represents the number of items that make up the list. It is as if you had declared an array of flowing-point numbers as double Distance[5] which represents a series of 5 distances. The second dimension of an array of characters represents the maximum number of characters that each item can have. To initialize a 2-dimensional array, assign an opening and a closing curly brackets to it. Inside of the curly brackets, provide each item between double-quotes. Here is an example:
#include <iostream> using namespace std;

int main()

{ char Country[3][20] = { "Afrique du Sud", "Australie", "Zimbabwe" };

return 0; }

Make sure that the number of items of your list is equal to or less than the first dimension. If this condition is not met, the compiler would display an error. For example, the following program will not compile because the declaration of the array specifies that the array is made of three items but is initialized with 6:
#include <iostream> using namespace std;

int main() { char Country[3][20] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

return 0; }

In the same way, make sure that each item of the array has a number of characters (or letters) that is equal to or less than the second dimension. The following program will not compile because two items of the array (the 1st and the last) have more than 10 letters after you had declared that the maximum number of letters of each item of the arrays would be 10 characters:
#include <iostream> using namespace std;

int main() { char Country[6][10] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

return 0;

To access an item of the 2-dimensional array of characters, provide its name followed by its index. The index here is from the first dimension because the first dimension specifies the number of items of the array. For example, you can access the 3rd item of the above Country array with Country[4]. The compiler does not need the dimension of each item to display it. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; cout << "\nCountry 1: " << Country[0]; cout << "\nCountry 2: " << Country[1]; cout << "\nCountry 3: " << Country[2]; cout << "\nCountry 4: " << Country[3]; cout << "\nCountry 5: " << Country[4]; cout << "\nCountry 6: " << Country[5];

cout << "\n\n"; return 0; }

This would produce:


Countries Names Country 1: Afrique du Sud Country 2: Australia Country 3: Zimbabwe Country 4: Sri Lanka

Country 5: Yemen Country 6: El Salvador

In the same way, you can use a for loop to scan the array, accessing each member by its position. Here is an example:
#include <iostream> using namespace std;

int main() { char Country[6][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

cout << "\n\n"; return 0; }

When you declare a two-dimensional array, yo do not have to know how many items the array is made of but you must know the maximum number of characters that each item can be mad of. This property of arrays can be used to leave the first square brackets empty:
#include <iostream> using namespace std;

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names";

for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

cout << "\n\n"; return 0; }

We saw earlier that, using a pointer to char, you do not have to specify the number of characters that composes an array. For a 2-dimensional array, you can let the compiler figure out how many items the array uses. To do this, when declaring the array, precede the name of the array with an asterisk. This will allow the compiler to locate the address of the first item and take over from there. Based on this, the above array can be declared as follows:
char *Country[15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

We also saw earlier that the name of an represents the address of the variable. In the same way, you do not have to find the item that has the highest number of characters and specify it as the second dimension of the array. You can let the compiler figure out this by letting the square brackets empty. By your initializing the array, the compiler would figure out how much space each item needs. Therefore, the above array can be declared as follows:
#include <iostream> using namespace std;

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

cout << "Countries Names"; for(int i = 0; i < 6; ++i) cout << "\nCountry " << i + 1 << ": " << Country[i];

cout << "\n\n"; return 0; }

Two-Dimensional Arrays of Characters and Functions When declaring and when defining a function that takes as argument a 2-dimensional array, the argument is passed with two pairs of square brackets. The first square bracket should be left empty although you are allowed to specify its dimension. This first pair of square brackets lets the compiler know the argument represents a group of strings. The second pair of square brackets must have the maximum characters that each item of the array has. Such a function can be declared and defined as follows:
void ShowCountries(char S[][15]);

When calling such a function, provide only the name of the array. The compiler can figure out the rest by referring to the definition of the function (of course, this is still your responsibility). Here is an example:
#include <iostream> using namespace std;

void ShowCountries(char S[][15]) { cout << "Countries Names";

for(int i = 0; i < 3; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country);

cout << "\n\n"; return 0; }

If you expect the function to also process the (whole) array, you can pass a second argument that would hold the actual number of items that composes the array passed as argument. Here is an example:
#include <iostream> using namespace std;

void ShowCountries(char S[][15], const int n) { cout << "Countries Names";

for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char Country[][15] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

cout << "\n\n"; return 0; }

You can also pass the argument as a pointer to char after declaring the array as such. This, of course, allows the compiler to better manage memory because it can figure out how many items are in the array and how much space each item needs. To pass an array as a pointer to char, when declaring and when defining the function, precede the name of the argument with an asterisk and type an empty pair of square brackets on the right side of the name of the argument. You can call this function the same way we did above:
#include <iostream> using namespace std;

void ShowCountries(char *S[], const int n) { cout << "Countries Names";

for(int i = 0; i < n; ++i) cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

cout << "\n\n"; return 0; }

Alternatively, when declaring and when defining the function, you can specify that the argument is a pointer to char:
#include <iostream> using namespace std;

void ShowCountries(char **S, const int n) { cout << "Countries Names";

for(int i = 0; i < n; ++i)

cout << "\nCountry " << i + 1 << ": " << S[i]; }

int main() { char *Country[] = { "Afrique du Sud", "Australia", "Zimbabwe", "Sri Lanka", "Yemen", "El Salvador" };

ShowCountries(Country, 6);

cout << "\n\n"; return 0; }

Introduction to Strings Defining a String A string is an array of characters whose last character is \0. A typical string, such as Pacifique, is graphically represented as follows: P a c i f i q u e \0 The last character \0 is called the null-terminating character. For this reason, a string is said to be null-terminated. The string library ships with a lot of functions used to perform almost any type of operation on almost any kind of string. Used under different circumstances, the string functions also have different syntaxes. The strings that you can use in your program may be defined in various libraries depending on your compiler but most of the time, they are available once you include the string library that is defined in the std namespace. For example, the functions we are about to review are part of the C language. The strings that are part of the (C++) Standard Template Library (STL) are defined in the string class of the std namespace. Based on this, most compilers make all these functions accessible once you include the string library and the std namespace in your program. String Manipulation Functions The C++ and its parent the C languages do not have a string data type. In C and C++, strings are created from arrays. Therefore, the C++ language relies on operations performed on the arrays of characters or pointers to char. The functions used for this purpose are numerous and you should know what they are used for. As a reminder, thanks to the features of arrays of characters and the friendship between arrays of

characters and strings, there are two main ways you can declare and initialize a string:
char *Thing = Telephone; char Major[] = Computer Sciences;

The Length of a String In many operations, you will want to know how many characters a string consists of. To find the number of characters of a string, use the strlen() function. Its syntax is:
int strlen(const char* Value);

The strlen() function takes one argument, which is the string you are considering. The function returns the number of characters of the string. Here is an example:
#include <iostream> using namespace std;

int main() { char *School = "Manchester United"; int Length = strlen(School);

cout << "The length of \"" << School << "\" is " << Length << " characters\n\n";

return 0; }

This would produce:


The length of "Manchester United" is 17 characters

The strcat() Function If you have two strings, to append one to another, use the strcat() function. Its syntax is:
char *strcat(char *Destination, const char *Source);

The strcat() function takes two arguments. The second argument, called the source string, is the string you want to add to the first string; this first string is referred to as the destination. Although the function takes two arguments. It really ends up changing the destination string by appending the second string at the end of the first string. This could be used to add two strings. Here is an example:

#include <iostream> using namespace std;

int main() { char *Make = "Ford "; char *Model = "Explorer";

cout << "Originally, Make = " << Make;

strcat(Make, Model);

cout << "\n\nAfter concatenating, Make = " << Make << endl; return 0; }

This would produce:


Originally, Make = Ford

After concatenating, Make = Ford Explorer

The strncat() Function Like the strcat() function, the strncat() function is used to append one string to another. The difference is that, while the strcat() considers all characters of the source string, the strncat() function allows you to specify the number of characters from the source string that you want to append to the destination string. This means that, if the source string has 12 characters, you can decide to append only a set number of its characters. The syntax is:
char* strncat(char* Destination, const char* Source, int Number);

Besides the same arguments as the strcat() function, the Number argument sets the number of characters considered from Source. To perform the concatenation, the compiler would count characters from left to right on the source string. Here is an example:
#include <iostream> using namespace std;

int main() { char *Make = "Ford "; char *Model = "Explorer";

cout << "Originally, Make = " << Make;

strncat(Make, Model, 3);

cout << "\n\nAfter concatenating, Make = " << Make; return 0; }

This would produce:


Originally, Make = Ford

After concatenating, Make = Ford Exp

Copying One String Into Another The strcpy() function is used to copy one string into another string. In English, it is used to replace one string with another. The syntax of the strcpy() function is:
char* strcpy(char* Destination, const char* Source);

This function takes two arguments. The first argument is the string that you are trying to replace. The second argument is the new string that you want to replace. There are two main scenarios suitable for the strcpy() function: To replace an existing string or to initialize a string. The following would initialize a string:
char CarName[20];

strcpy(CarName, "Toyota Camry");

cout << "Car Name: " << CarName;

If you have two strings and copy one into another, both strings would hold the same value:
#include <iostream> using namespace std;

int main() { char carName1[] = "Ford Escort"; char carName2[] = "Toyota 4-Runner";

cout << "The String Copy Operation"; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2;

strcpy(carName2, carName1);

cout << "\n\nAfter using strcpy()..."; cout << "\nFirst Car: " << carName1; cout << "\nSecond Car: " << carName2 << endl;

return 0; }

This would produce:


The String Copy Operation First Car: Ford Escort Second Car: Toyota 4-Runner

After using strcpy()... First Car: Ford Escort

Second Car: Ford Escort

The strncpy() Function The strncpy() function works like the strcpy() function. As a difference, the strncpy() function allows you to specify the number of characters that the compiler would copy from the source string. Here is the syntax:
char* strncpy(char* Destination, const char* Source, int Number);

The Number argument specifies the number of characters that will be copied from the Source string. Here is an example:
#include <iostream> using namespace std;

int main() { char CarName1[] = "Ford Escort"; char CarName2[] = "Toyota 4-Runner";

cout << "The String Copy Operation"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2;

strncpy(CarName2, CarName1, 8);

cout << "\n\nAfter using strncpy() for 8 characters"; cout << "\nFirst Car: " << CarName1; cout << "\nSecond Car: " << CarName2 << endl;

return 0; }

This would produce:


The String Copy Operation

First Car: Ford Escort Second Car: Toyota 4-Runner

After using strncpy() for 8 characters First Car: Ford Escort Second Car: Ford Esc-Runner

The strdup() Function The strdup() function is used to make a copy of create a duplicate of that string. Its syntax is:
char* strdup(const char *S);

This function takes as an argument the string you want to duplication and returns the duplicated string.
#include <iostream> using namespace std;

int main() { char *FirstName1 = "Charles"; char *FirstName2 = "Andy"; char *LastName1 = "Stanley"; char *LastName2;

LastName2 = strdup(LastName1);

cout << "Father: " << FirstName1 << ' ' << LastName1 << endl; cout << "Son: " << FirstName2 << ' ' << LastName2;

return 0; }

This would produce:


Father: Charles Stanley Son: Andy Stanley

Comparing Strings Various routines are available for strings comparison. The C-String library is equipped with functions that perform the comparisons by characters. Alternatively, some compilers like Borland C++ Buider ships with additional multiple functions to perform these comparisons on null-terminated strings. The strcmp() Function The strcmp() function compares two strings and returns an integer as a result of its comparison. Its syntax is:
int strcmp(const char* S1, const char* S2);

This function takes two strings, S1 and S2 and compares them. It returns

A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

#include <iostream> using namespace std;

int main() { char *FirstName1 = "Andy"; char *FirstName2 = "Charles"; char *LastName1 = "Stanley"; char *LastName2 = "Stanley";

int Value1 = strcmp(FirstName1, FirstName2); int Value2 = strcmp(FirstName2, FirstName1); int Value3 = strcmp(LastName1, LastName2);

cout << "The result of comparing " << FirstName1

<< " and " << FirstName2 << " is\t" << Value1 << endl; cout << "The result of comparing " << FirstName2 << " and " << FirstName1 << " is\t" << Value2 << endl; cout << "The result of comparing " << LastName1 << " and " << LastName2 << " is\t" << Value3;

return 0; }

This would produce:


The result of comparing Andy and Charles is -2 The result of comparing Charles and Andy is 2 The result of comparing Stanley and Stanley is 0

The strncmp() Function The strncmp() function compares two strings using a specified number of characters and returns an integer as a result of its findings. Its syntax is:
int strncmp(const char* S1, const char* S2, int Number);

This function takes three arguments. The first two arguments are the strings that need to be compared. The 3rd argument specifies the number of characters considered for the comparison. It returns

A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

The stricmp() Function The stricmp() function compares two strings without regard to their case. In other words, this function does not take into consideration if there is a mix of uppercase and lowercase characters in the strings. The syntax of the function is:
int stricmp(const char* S1, const char* S2);

This function takes two strings, S1 and S2 and compares them. It returns

A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

The strnicmp() Function The strnicmp() function compares two strings without regard to their case but considers only a specified number of characters. The syntax of the function is:
int strnicmp(const char* S1, const char* S2, int n);

This function takes two strings, S1 and S2 and compares them. It returns

A negative value if S1 is less than S2 0 if S1 and S2 are equal A positive value if S1 is greater than S2

Working With Individual Characters The strchr() Function The strchr() function looks for the first occurrence of a certain character in a string. Its syntax is:
char* strchr(const char* S, char c);

This function takes two arguments. The second argument specifies what character to look for in the first argument which is a string. If the character c appears in the string S, the function would return a new string whose value starts at the first occurrence of c in S. If the character c does not appear in the string S, then the function would return NULL. The strrchr() Function The strrchr() function examines a string starting at the end (right side) of the string and looks for the first occurrence of a certain character. Its syntax is:
char* strrchr(const char* S, char c);

The first argument is the string that needs to be examined. The function will scan the string S from right to left. Once it finds the first appearance of the character c in the string, it would return a new string whose value starts at that first occurrence. If the character c does not appear in the string S, then the function would return NULL. Working With Sub-Strings The strstr() Function The strstr() function looks for the first occurrence of a sub-string in another string and returns a new string as the remaining string. Its syntax is:
char* strstr(const char* Main, const char *Sub);

The first argument of the function is the main string that would be examined. The function would look for the second argument, the Sub string appearance in the main string. If the Sub string is part of the Main string, then the function would return a string whose value starts at the first appearance of Sub and make it a new string. If Sub is not part of the Main string, the function would return a NULL value. Working With Character Cases The strlwr() Function The strlwr() function is used to convert a string to lowercase. Its syntax is:

char *strlwr(const char *S);

This function takes, as argument, the string that needs to be converted. During conversion, if a Latin character were in uppercase, it would be converted to lowercase. Otherwise, it would stay as if. This means any symbol that is not a readable character would not be converted.
#include <iostream> using namespace std;

int main() { char CustomerAddress[] = "4812 LOCKWOOD Drive #F04";

cout << "Customer Address: " << CustomerAddress << endl;

char *ShippingAddress = strlwr(CustomerAddress);

cout << "Shipping Address: " << ShippingAddress << endl;

return 0; }

This would produce:


Customer Address: 4812 LOCKWOOD Drive #F04 Shipping Address: 4812 lockwood drive #f04

The strupr() Function The strupr() function is used to convert a string to uppercase. Its syntax is:
char *strupr(const char *S);

Each lowercase character in the functions argument, S, would be converted to uppercase. Any character or symbol that is not in lowercase would not be changed.
#include <iostream> using namespace std;

int main() {

char Drink[] = "100% Apple Juice"; char *SayItLoud;

cout << "What is that drink? " << Drink << endl;

SayItLoud = strupr(Drink); cout << "Say it loud: " << SayItLoud << endl;

return 0; }

This would produce:


What is that drink? 100% Apple Juice Say it loud: 100% APPLE JUICE

Formatting Strings The sprintf() Function The sprintf() function is used to format data and specify how it should display. Its syntax is:
int sprintf(char* Buffer, const char* S, Arguments);

This function takes at least two arguments and could take more. The first argument is a nullterminated string that could display one or a few words and the formula to use when displaying the second or more argument. To display a value as part of the Buffer, type a double-quote followed by the string if any, followed by the % sign, follow by one of the following characters:
Character s c Used to Display A string A character Character f d Used to Display Floating-point value An integer

Data Input/Output Data Display Introduction The values and expressions used in C++ are displayed using the cout extractor. To make the

displaying of data more realistic, the cout is configured to handle or format data to any desired result. While the cout (as a class) is defined in the iostream file, some other files provide other extensive techniques for displaying data to the console. The C language also is equipped with other formatting functions used for the same purpose. The ability to create a program made of mixed C and C++ language enhances these formatting possibilities. General Display Techniques With cout The ostream class (although we have not learned about classes yet, we can explore them without knowing what a class is) has allowed us so far to display items on the console screen. It is from the ios library and commands all techniques of data output to C++ console applications. The cout we have used so far is a child of the ostream library. Using it, we have found out that we can display almost any type of value. For example, it can be used to display:

A word or sentence, called a string: cout << "Major = South African History"; A character: cout << 'G'; A short integer: cout << -10540; An integer: cout << 242; A long integer: cout << 46300540; A floating number: cout << 126.50; Or a double-precision number: cout << 440005.55;

Instead of displaying a value just using the cout extractor, you can first declare and initialize a variable before displaying its value. Like the ostream, the cout is also referred to as an object. Besides the cout and the extraction operator << used to display a character, the cout can be used to display a (one) character. To do this, type cout followed by a period and followed by the put() member function. The syntaxes of the put() function are:
ostream& put(char);

ostream& put(unsigned char); ostream& put(signed char);

The character must be included between parentheses and single-quotes. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //--------------------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { cout.put('P'); cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

If the character is initialized from a variable, type the name of the variable between parentheses:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //--------------------------------------------------------------------------#pragma argsused int main(int argc, char* argv[]) { char Category = 'T'; cout.put(Category); cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The character can also come from a variable requested from the user. The cout.write() Function If you want to display a whole string, use the write() function. This function requires two arguments. First, you must specify the string that is used as the source. Second, the compiler needs to know how many characters from the source will be displayed (or considered). Here are two examples:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop //--------------------------------------------------------------------------#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Peripheral[] = "Digital Camera"; // First example of using the write() member function of the cout class cout.write("The 5th Floor", 13); cout << endl; // Second example of using the write() function cout.write(Peripheral, 8); cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Although the second argument is used to display a fixed number of characters, if you want to display the whole string, you must make sure the value of the second argument is greater than or equal to the length of the source string. Instead of visually counting the number of characters, which could lead to a mistake, you can use the sizeof operator to get the length of the string:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Peripheral[] = "Digital Camera"; int Count = sizeof(Peripheral) / sizeof(char);

cout.write(Peripheral, Count);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Data Display Functions: puts() The C++ (Builder) compiler ships with other files that provide many other functions that can be used to control how data displays on the screen. One of these files is the stdio.h header. The puts() function is used to display a string on the console. Its syntaxes are:
int puts(const char *Str);

The Str argument must be a regular string enclosed in double-quotes. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio>

using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

puts("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

cout << "\nYour answer was: " << Answer;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The puts() function lacks the formatting possibilities of cout. It is destined to only display a single string. To display more complex strings, you can combine it with other operators or functions. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

puts("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

puts("\nYour answer was: "); cout.put(Answer);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The string to display on a puts() function can also originate from a declared and initialized variable. In this case, you would provide the name of the variable as the argument to the function. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std;

#pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Question[] = "Do you consider yourself a hot-tempered individual? "; char Answer;

puts(Question); cin >> Answer;

puts("\nYour answer was: "); cout.put(Answer);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The cputs() Function The puts() function positions the cursor of the subsequent line. If you find this annoying, you can use the cputs() function. The cputs() function is used to display a string on the console. Its syntax is:
int cputs(const char *Str);

To display a string using the cputs() function, pass a string as the argument. The cputs() function requires the conio header file. Here are two examples:

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer;

cputs("Do you consider yourself a hot-tempered individual? "); cin >> Answer;

cputs("\nYour answer was: "); cout.put(Answer);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

If the string is from a variable, provide the name of the variable as argument. The printf() Function

The printf() function is mostly used in the C language programs. By default, it is used to display a string on the console. Its simpler syntax is:
int printf(const string);

To display a string using the printf() function, simply enclose it between double-quotes, as the functions argument. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { printf("Welcome to College Park Auto-Parts");

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The cprintf() Function While the printf() is a function of the stdio.h file, the conio.h library provides an alternative to display a string on the console. The function used is cprintf() and its basic syntax is:

int cprintf(const string); This function behaves the same way as the stdio.hs printf() function. Controlling and Formatting Data Output The Width of Data Display The width() function is used to set the amount of space needed to display an item on the console. Its syntax is:
int width(); int width(int Count);

The first version of this function displays the intended value as is. The second version takes one integer as argument, Count. In order to display the intended value that could be an array of characters, an integer or a floating number, the compiler would count the number of characters (for a char or a string) or the number of digits (for an integer or a float, including the period for decimals). If the value of the argument you supplied, Count, is less than or equal to the number of characters or digits, the compiler would ignore your argument, Count, and display the intended value. If the value argument is greater than the number of characters or digits, the compiler would display the intended value using the total value of the argument, Count, but leaving empty spaces on the left of the intended value. The value to display comes after calling the width() function. If you are displaying only one value, the scenario above would apply straight forward. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) {

int Value = 782;

cout.width(6); cout << Value;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

To display various values, you can call the width() function for each and they can use different width values as in the following example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;

cout.width(8); cout << Value1 << endl;

cout.width(14); cout << Value2 << endl; cout.width(10); cout << Value3 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

An alternative to using the width() function is to call the setw() function: int setw(int w); This function takes an integer argument that specifies the amount of space used to display the intended value. Like the width() function, the setw() function can be used to format one value at a time. Here is an example of using it:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) {

double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12;

cout.width(16); cout << Value1 << endl; cout << setw(8) << Value2 << endl; cout << setw(12) << Value3 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Filling the Empty Space As we have seen already, the compiler leaves empty spaces on the left side of the displaying value if the width is greater than the needed space. If you do not want that space to be empty, you can fill it with any character you want. To do that, call the fill() function: char fill(); char fill(char c); The second fill() function takes one argument as the character that would be used in place of the empty spaces. The argument is a character that can be included between single-quotes. If no fill() function was called previously, the second version displays the intended value as is. If there was a previous call to the fill(char c) version that takes a character argument, the first version, fill(), immediately following would still keep the argument of the previous call to fill(), then empty it. In other words, if there is another call to the fill() version without argument, no character would be displayed, until a new call to the fill(char c) function. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 25.56, Value3 = 28478.12, Value4 = 10.05;

cout.width(12); cout << Value1 << endl; cout.width(12); cout.fill('#'); cout << Value2 << endl; cout.width(12); cout.fill(); cout << Value3 << endl; cout.fill(); cout << Value4 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Like the fill() function, the iomanip library provides the setfill() function to fill out empty spaces on a line formatted with the setw() function. The syntax of the setfill() function is:
int setfill(char c);

This function takes one character as argument. This character would be used to fill out the empty spaces on the left of a value displayed on a subsequent cout. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Value1 = 6.5, Value2 = 28478.12, Value3 = 35.25; string WebSite = ".functionx.com";

cout << setw(16) << setfill('%'); cout << Value1 << endl; cout << setw(8) << setfill('@') << Value2 << endl; cout << setw(12) << Value3 << endl; cout << setw(17) << setfill('w') << WebSite << endl;

cout << "\nPress any key to continue..."; getch(); return 0; }

//---------------------------------------------------------------------------

The dec, hex, and oct Operators The most usual way to show an integer number on the console is to display it as is. To display a variable that has been declared and initialized as int Value = 152; you would write: cout << Value; The compiler would take care of displaying it. If you have an integer in decimal format and would like to display its equivalent hexadecimal representation, use the hex operator as follows:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Value = 242;

cout << "Value = " << Value << endl; cout << "Value = " << hex << Value << endl;

cout << "\nPress any key to continue...";

getch(); return 0; } //---------------------------------------------------------------------------

If you have a hexadecimal integer and would like to display it in a decimal format, simply use the cout operator followed by the value. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { cout << "Number = " << 0xFE28D;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Although all integers are displayed in decimal format by default, you can explicitly ask the compiler to reinforce that notation. You can also display the same value in either format as follows:

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Variable = 28045;

cout << "Declared Variable: " << Variable << endl; cout << "In decimal: " << dec << Variable << endl; cout << "In hexadecimal: " << hex << Variable << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

This would produce:


Declared Variable: 28045 In decimal: 28045 In hexadecimal: 6d8d

Press any key to continue...

Although the hex and dec words are used as operators, they are indeed functions that each takes one argument. Such an argument is passed by reference, which means the argument retains the new value after being operated on. For example, if you pass a decimal integer to the hex function, the argument will be maintained as hexadecimal. That is what happens with the following example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Variable = 28045;

cout << "Declared Variable: " << Variable << endl; cout << "In decimal: " << dec << Variable << endl; cout << "In hexadecimal: " << hex << Variable << endl; cout << "Declared Variable: " << Variable << endl;

cout << "\nPress any key to continue..."; getch(); return 0; }

//---------------------------------------------------------------------------

This would produce:


Declared Variable: 28045 In decimal: 28045 In hexadecimal: 6d8d Declared Variable: 6d8d

Press any key to continue...

The uppercase Attribute As you have found out, the hex attribute is used to display the hexadecimal equivalent of a decimal number, but such a number displays in lowercase. To display the hexadecimal letters to uppercase, include the uppercase attribute. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int SayIt = 12;

cout << hex << uppercase << SayIt << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The uppercase attribute can precede or succeed the hex attribute, as illustrated by the following example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { long Value = 3874238;

cout << uppercase << hex << Value << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The setiosflags() Function The width() member function and the setw() functions are typically used to right-align the value(s) displayed that otherwise would be left aligned. If you want to explicitly left align a value, use the setioflags() function. This function takes only one argument as the type of flags used to display data. In order to use the setiosflags() function, you must qualify its flags using the library in which the flag is defined. The ios::left flag is used to left-align a value. Here is a simple example that displays an integer:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Series = 2014;

cout << setiosflags(ios::left) << Series;

cout << "\n\nPress any key to continue..."; getch(); return 0; }

//---------------------------------------------------------------------------

The resetiosflags() Function After calling the setiosflags() function, any value displayed would follow the rule of that function. To remove the formatting set by the setiosflags(), use the resetiosflags() function, usually with the same argument:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Series = 2014; double Price = 12.95;

cout << setiosflags(ios::left) << Series << endl; cout << resetiosflags(ios::left) << setw(8) << Price;

cout << "\n\nPress any key to continue..."; getch(); return 0; }

//---------------------------------------------------------------------------

Formatting Floating-Point Numbers In most programs that use precise numbers, you need to be able to format your values to display appropriately. This is made possible with the use of the setprecision() function:
int setprecision(int p);

This function takes one argument as the number of decimal places displayed after the period of the floating number. In order to effectively use the setprecision() funciton, first call the setiosflags() function with the appropriate flag. The ios::fixed flag allows you to specify the exact number of decimal values used in the setprecision() function. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Price = 0.5;

cout << setiosflags(ios::fixed) << setprecision(2) << Price << endl;

cout << "\n\nPress any key to continue..."; getch(); return 0;

} //---------------------------------------------------------------------------

Since the setiosflags() and the setprecision() functions apply their formatting to all values set after they have been called, you can use them once and format your other values. That is, until you call these functions again. This is used in the following example:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Qty1 = 2, Qty2 = 5, Qty3 = 4, Qty4 = 1; double Price1 = 0.5, Price2 = 1.25, Price3 = 2.95, Price4 = 1.65; double Total1 = Qty1 * Price2, Total2 = Qty4 * Price3, Total3 = Qty2 * Price1, Total4 = Qty3 * Price4;

cout << setiosflags(ios::fixed) << setprecision(2);

cout << "Total 1 = " << Total1 << endl; cout << "Total 2 = " << Total2 << endl; cout << "Total 3 = " << Total3 << endl; cout << "Total 4 = " << Total4 << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

You can also display floating numbers using a scientific format. To do that, set the flag of the setiosflags() function to ios::scientific. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <iomanip> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Pop = 25.44059, Distance = 212.625, MaxExp = 709.78222656;

cout << setiosflags(ios::scientific) << setprecision(2); cout << "PI = " << Pop << endl; cout << "Distance = " << Distance << endl; cout << "Exponent = " << MaxExp << endl;

cout << "\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

This would produce:


PI = 2.54e+01 Distance = 2.13e+02 Exponent = 7.10e+02

Press any key to continue...

C How to Display Data The C language is the parent of C++. As such, C++ inherits what is available from its parent C. This flexibility also allows you to mix the way things are done in C and the features that are available in C++. Although C is C++ parent, you do not need to know (anything) about C in order to program in C++ (in fact, you should not know anything about C, at all). Nevertheless, we will review these features transparently and we will be concerned only with the reason we are here: how to program in C++. To format the display of data in C++, the cout operator (once again, it is a class) is complete. In some circumstances, and this will become common when writing applications using some of Borland classes (such as AnsiString), you will need to know how other objects format data. The most common function used to display data in C, and some legacy C++ code, is the printf() function. As flexible as it is, it does not use the type of syntax we are already getting used to in C++. From a C++ stand point, to display data using the functions, everything depends on how you want data

to appear. Data types are divided in categories: characters, integers, floating-point numbers, and strings. To display a particular type, you type the percent operator %, followed by the category of data. An example would be %d. To display a character, use the %c format to represent a character variable. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Gender = 'M';

printf("Member Gender: %c", Gender);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

To display an integer, use the %operator with one of the following tags: Tag d Integer Type to Display signed decimal integer

i o u x X Here is an example:

signed decimal integer unsigned octal integer unsigned decimal integer unsigned hexadecimal int (with a, b, c, d, e, f) unsigned hexadecimal int (with A, B, C, D, E, F)

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Number = 120;

printf("Number: %d", Number);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

To display a floating-point number, use the % operator with one of the following formats:

Tag f e

g E G Here is an example:

To display signed value of the form [-]dddd.dddd signed value of the form [-]d.dddd or e[+/]ddd signed value in either e or f form, based on given value and precision. Trailing zeros and the decimal point are printed if necessary. Same as e; with E for exponent Same as g; with E for exponent if e format used

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Distance = 272.44;

printf("Distance: %f", Distance);

cout << "\n\nPress any key to continue..."; getch(); return 0;

} //---------------------------------------------------------------------------

To set the number of decimal places after the period, type the % operator, followed by a period, followed by an integer for the number of decimal places desired, followed by the desired tag. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { double Floater = 3255.01265;

printf("Floater: %.3f", Floater);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

To display a string, use the %s format. Here is an example:

//--------------------------------------------------------------------------#include <iostream> #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char FIFA[] = "Federation Internationale de Football Association";

printf("World Cup Supervisor: %s", FIFA);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Data Input Using cin Data input in C++ is performed using the cin operator (cin also is a class). The cin is configured with so much flexibility (in C++, we consider that it is overloaded; in reality, it is the >> operator that is overloaded) that it can retrieve any type of declared regular variable. This includes integers, characters, floating-point numbers, or arrays of characters. Here are examples of variables that the cin can handle:
//--------------------------------------------------------------------------#include <iostream> #include <conio>

using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { cout << "Enter a natural number: "; int Natural; // Retrieve an integer cin >> Natural;

cout << "Type a decimal number: "; float Floater; // Requesting a floating pointing number cin >> Floater;

cout << "Type another decimal number: "; double Precision; // Retrieving a double-precision number cin >> Precision;

cout << "Are you ready for C++ (y=Yes/n=No)? "; char Answer; // Requesting a character cin >> Answer;

cout << "I mean, are you really ready (Type Yes or No)? "; char Explicit[10]; // Retrieving a word cin >> Explicit;

cout << "\nHere is what we got from you"; cout << "\nNatural Number: " << Natural; cout << "\nFloating Number: " << Floater; cout << "\nDouble Precision: " << Precision;

if( Answer == 'y' || Answer == 'Y' ) cout << "\nYou are ready for C++"; else cout << "\nYou are still not committed to C++";

cout << "\nYour readiness for C++: " << Explicit;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

The gets() Function The gets() function, as its name implies, is used to retrieve a string from the user. This function can receive a string of almost any length, depending on how you declare the string. To use the gets() function to request a string, include the stdio.h header file to your source. After declaring the string variable, provide it as argument to the gets() function. Here is an example:

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Answer[80];

puts("Are you ready to rumbleeeeee? "); gets(Answer);

cout << "\nThe audience response: " << Answer;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Here is an example of running the program:


Are you ready to rumbleeeeee? yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

The audience response: yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy

Press any key to continue...

C How to Input Data To request data from the user, or to retrieve it somehow, you can use the scanf() function that is part of the stdio.h file. To use this function, you must provide two pieces of information. First the function needs to know the type of variable the function is expecting. Each data type is represented by a letter as follows: Character c d e f g h i o s u x Used for A single character An integer A floating-point number A floating-point number A floating-point number A short integer A decimal, a hexadecimal, or an octal integer An octal integer A string followed by a white space character An unsigned decimal integer A hexadecimal integer

When calling the scanf() function to retrieve a specific value, the appropriate character must be preceded by an ampersand % and both must be included in double-quotes. For example, to request an integer, you would write %d. The second piece of information the function needs is the name of the declared variable. Because you are planning to change the value of the variable, it must be passed by reference. To use the scanf() function, you can include it in a C program. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { float Number;

printf("Type a number: "); scanf("%f", &Number); printf("\nYou typed: %f\n", Number);

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Here is an example of running the program:


Type a number: 145.50

You typed: 145.500000

Press any key to continue...

You can also mix C functions, such as printf() or scanf() in your C++ program as you see fit. For example, you can retrieve values using either cin or scanf() to retrieve any value. In the same way, you can use scanf(), cin, or gets() when requesting a string. Here is an example:
//---------------------------------------------------------------------------

#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char FullName[32]; char Gender; int Books;

cout << "Type your full name: "; gets(FullName); cout << "Type your gender (m=Male/f=Female): "; cin >> Gender; cout << "How many books do you own? "; scanf("%d", &Books);

cout << "\nWell, " << FullName << ", with " << Books << " books, it looks like you read a lot! ";

if( Gender == 'm' || Gender == 'M' ) puts("You are the man"); else

puts("You go, girl");

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Here is an example of running the program:


Type your full name: Jacob Desvarieux Type your gender (m=Male/f=Female): m How many books do you own? 84

Well, Jacob Desvarieux, with 84 books, it looks like you read a lot! You are the man

Press any key to continue...

Ending a Program

Exiting a Program

Many of the applications we have written so far stopped when the compiler found the return 0; line at the end of the main() function. In some circumstances it will be necessary to stop a program from a particular function if a bad or unexpected situation occurs. This is handled by the exit() function. Its syntax is:
void exit(int Status);

When called from anywhere, the exit() function closes all other functions and stops the program. The argument you pass as an integer determines how successful the termination occurred. If the Status is passed as 0, the program terminated successfully. Any other value of Status indicates that there was an error during the termination. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------char __fastcall GetAnswer() { char Answer;

cout << "Do you consider yourself a hot-tempered individual(y=Yes/n=No)? "; cin >> Answer;

Answer = tolower(Answer);

if( Answer != 'y' && Answer != 'n' ) exit(0); else return Answer;

return 'n'; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { char Ans;

Ans = GetAnswer();

if( Ans == 'y' || Ans == 'Y' ) { cout << "\nThis job involves a high level of self-control."; cout << "\nWe will get back to you."; } else cout << "\nYou are hired!";

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Alternatively, you can use the _exit() function to stop the program. Its syntax is:
void _exit(int Status);

As opposed to the exit() function that closes all functions upon exiting, the _exit() function stops the program without closing the other functions. The value of the Status argument determines how the program terminates. If the argument is passed with 0, the function would terminate successfully. Any other value indicates an error. Here is an example:

//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused //--------------------------------------------------------------------------int __fastcall NumberRequest() { int Number;

cout << "Type a number between 1 and 3 (included): "; cin >> Number;

if( Number >= 1 && Number <= 3 ) return Number; else _exit(0);

return 0; } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { int Nbr;

Nbr = NumberRequest(); cout << "Your number was: " << Nbr;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Notice that the sentence in the main() function executes only if the other function did not exit because of a wrong return value. Aborting a Program Sometimes a program terminates with a message box sent by the operating system. An example would be when a user is asked to provide a floating-point number but types a string and the program is supposed to multiply the provided value by another number. The program would stop or hang and display a message of abnormal termination. You can also create your own abnormal termination using the abort() function. Its syntax is:
void abort(void);

When called, the abort() function terminates the program and sends an error message to the operating system. The OS uses different codes to identify these types of errors. Upon exiting, the abort() function terminates with an error code of 3. When the operating system receives it, it displays a message box. You can click one of the buttons. If you click Ignore, the operating system can let you know that there was an abnormal termination. Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused void __fastcall ProcessAnswer() { char Sitting;

cout << "Are you sitting down now(y/n)? "; cin >> Sitting;

Sitting = toupper(Sitting);

if( Sitting == 'Y' ) cout << "\nWonderful!!!"; else if( Sitting == 'N' ) cout << "\nCould you please sit down for the next exercise?"; else abort(); } //--------------------------------------------------------------------------int main(int argc, char* argv[]) { cout << "For the next exercise, you need to be sitting down\n"; ProcessAnswer();

cout << "\n\nPress any key to continue..."; getch();

return 0; } //---------------------------------------------------------------------------

Terminating a Program If something bad happens in your program, the program is prepared to stop it. We will learn about some of these unusual but possible situations when studying exception handling. Nevertheless, if you suspect such a thing and would like to stop the program, you can use one of the exit(), _exit(), or abort() functions we have just seen. Alternatively, you can stop a program using the terminate function. Its syntax is:
void terminate();

You can call the terminate() function the same way we did with the exit() or abort() functions. Accessory Functions Borland C++ Builder ships with various types of functions to help you customize and improve your application and its behavior. Some of the functions are part of the C/C++ language. Some others were created by Borland. And some other functions are built in the operating system. Clearing the Screen With system() When an application is running (that is, a console application), for example while a user is performing data entry, the program processes one statement at a time in a top-down approach. When the user finishes, you will usually display the result on the screen. If the program is long, at one time it would fill out the screen and this could make the displayed result confusing with the data processing. There are two basic ways you can clear the screen in Borland C++ Builder console application. The simplest technique consists of calling the system() function with the string argument "cls". The syntax of the system() function is:
int system(const char *Argument);

Here is an example:
//--------------------------------------------------------------------------#include <iostream> #include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused int main(int argc, char* argv[]) { char FirstName[12], LastName[12];

cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName;

system("cls");

cout << "Full Name: " << FirstName << " " << LastName;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Borland's Function of Clearing the Screen Another technique used to clear the screen consists of using a special function that a Borland created: the clrscr() function. The clrscr() function is part of the conio library. The clrscr() function is not part of the C++ Standard. The syntax of this function is as follows:
void clrscr(void);

The clrscr() function does not take an argument and does not return a value. It is simply used to empty the screen. Here is an example of using it:
//--------------------------------------------------------------------------#include <iostream>

#include <conio> using namespace std; #pragma hdrstop

//---------------------------------------------------------------------------

#pragma argsused int main(int argc, char* argv[]) { char FirstName[12], LastName[12];

cout << "Enter First Name: "; cin >> FirstName; cout << "Enter Last Name: "; cin >> LastName;

clrscr();

cout << "Full Name: " << FirstName << " " << LastName;

cout << "\n\nPress any key to continue..."; getch(); return 0; } //---------------------------------------------------------------------------

Introduction to Exception Handling Foundations of Exceptions Introduction During the execution of a program, the computer will face two types of situations: those it is prepared to deal with and those it doesnt like. Imagine you write a program that asks the user to supply two

numbers to perform a calculation. Here is such a program:


#include <iostream> using namespace std; int main() { double a, b, c; // Request two numbers from the user cout << "Please provide two numbers\n"; cout << "First Number: "; cin >> a; cout << "Second Number: "; cin >> b; // Multiply the numbers and display the result c = a * b; cout << "\n" << a << " * " << b << " = " << c << "\n\n"; return 0; }

This is a classic easy program. When it comes up, the user is asked to simply type two numbers; the program would use them to perform a multiplication and display the result. Imagine that a user, thanks to his infinite creativity or because of just a mistake, decides to type the name of a country or somebodys telephone number as one of the requested values. Since a program such as this one is not prepared to multiply two strings or one number to a string (actually, using operator overloading, you can tell the compiler how to perform almost any type of operation on the values of your program), it would not know what to do. The only alternative the compiler would have is to send the problem to the operating system, hoping that the OS would know what to do. What actually happens is that, whenever the compiler is handed a task, it would try to perform the assignment. If it cant perform the assignment, for any reason it is not prepared for, it would throw an error. As a programmer, if you can anticipate the type of error that could occur in your program, you can catch the error yourself and deal with it by telling the compiler what to do when this type of error occurs.

Exceptional Behaviors An exception is a situation that would be unusual for the program that is being processed. As a programmer, you should anticipate any abnormal behavior that could be caused by the user entering wrong information that could otherwise lead to unpredictable results. An error result or an unpredictable behavior on your program not caused by the operating system but that occurs in your program is called an exception. The ability to deal with a programs eventual abnormal behavior is called exception handling. C++ provides three keywords to handle an exception. 1. Trying the normal flow: To deal with the expected behavior of a program, use the try

keyword as in the following syntax: try {Behavior} The try keyword is required. It lets the compiler know that you are anticipating an abnormal behavior and will try to deal with it. The actual behavior that needs to be evaluated is included between an opening curly bracket { and a closing curly bracket }. Inside of the brackets, implement the normal flow that the program should follow, at least for this section of the code. 2. Catching Errors: During the flow of the program as part of the try section, if an abnormal behavior occurs, instead of letting the program crash or instead of letting the compiler send the error to the operating system, you can transfer the flow of the program to another section that can deal with it. The syntax used by this section is: catch(Argument) {WhatToDo} This section always follows the try section and there must not be any code between the trys closing bracket and the catch section. The catch keyword is required and follows the try section. The catch behaves a little like a function. It uses an argument that is passed by the previous try section. The argument can be a regular variable or a class. If there is no argument to pass, the catch must at least take a three-period argument as in catch(). The behavior of the catch clause starts with an opening curly bracket { and ends with a closing curly bracket }. The inside of the brackets is called the body of the catch clause. Therefore, use the body of the catch to deal with the error that was caused. Combined with the try block, the syntax of an exception would be:
try { // Try the program flow } catch(Argument) { // Catch the exception }

3. Throwing an error: There are two main ways an abnormal program behavior is transferred from the try block to the catch clause. This transfer is actually carried by the throw keyword. Unlike the try and catch blocks, the throw keyword is independent of a formal syntax but still follows some rules. Facing an Exception An exception is a behavior that should not occur in your program but is likely to show up. The simplest exception looks like a conditional statement and here is an example:
#include <iostream> using namespace std; int main() {

int StudentAge; cout << "Student Age: "; cin >> StudentAge; try { if(StudentAge < 0) throw; cout << "\nStudent Age: " << StudentAge << "\n\n"; } catch(...) { } cout << "\n"; return 0; }

If you run this program and type a positive integer for the students age, the program would respond by displaying the student age. Thats a good outcome. If you run the program and type a letter or any character, the compiler would display the student age as 0. This is the first proof that the compilers are already configured to deal with some abnormal behavior of a program. When the throw keyword is written by itself, it is a way of asking the compiler to send the exception to another handler. In fact, if there is no other handler written by you, the processing would be handed to the operating system. In this case, if you run the program and type a negative integer, since the program is not prepared to handle the exception itself, because of the presence of a single throw, the operating system would take over and display its own message. This would be abnormal program termination on a Microsoft Windows operating system.
#include <iostream> using namespace std; int main() { double Number1, Number2, Result; // Request two numbers from the user cout << "Please provide two numbers\n"; try { cout << "First Number: "; cin >> Number1; cout << "Second Number: "; cin >> Number2; if( Number2 == 0 ) throw; // Perform a division and display the result Result = Number1 / Number2;

cout << "\n" << Number1 << " / " << Number2 << " = " << Result << "\n\n"; } catch(...) { } return 0; }

Test the program and supply two valid numbers such as 126.45 and 5.52 Return to your programming environment and test the program again. This time, type 0 for the second number. Predicting Exceptions Writing Local Exceptions Imagine you write a program that requests a students age from the user. As we know, everybodys age is positive. Therefore, we need to figure out what to do if the user types a negative number. The expression that checks whether the number entered is positive can be written as:
if(StudentAge < 0)

If the condition is true, the minimum you can do is to send the produced error away. This is done with the throw keyword:
try { if(StudentAge < 0) throw; }

Whenever an exception occurs, and whenever you use the try keyword to try an expression, you must transfer control to a catch block. This is where you should display your own message for the error. Here is an example:
#include <iostream.h> int main() { int StudentAge; try { cout << "Student Age: "; cin >> StudentAge; if(StudentAge < 0) throw "Positive Number Required"; cout << "\nStudent Age: " << StudentAge << "\n\n"; } catch(const char* Message)

{ cout << "Error: " << Message; } cout << "\n"; return 0; }

This program starts with the try block that asks the user to enter a positive number. If the user enters an invalid value, the program examines the throw keyword. This throw appears to display a string. The compiler registers this string and since there was an exception, the program exits the try block (it gets out of the try block even if the rest of the try block is fine) and looks for the first catch block it can find. If it finds a catch that doesnt take an argument, it would still use the catch. Otherwise, you can use the catch block to display the error string that was sent by the throw keyword. In the example above, the catch uses a string as a pseudo-argument and displays it using a cout extractor. In the example above, the catch block is configured to display a string. Lets consider the classic division by zero operation. The division by zero is dealt with at different levels. The processor (Intel, AMD, etc) is configured not to allow it. The operating system is also prepared for it. Finally, the compiler has its own interpretation of this operation. Nevertheless, if you suspect it to occur in your program, you can take appropriate measures. When preparing to deal with division by zero, the main idea is to compare the denominator with 0. This comparison should be performed in a try block. If the comparison renders true, you should avoid the operation and hand the error (exception) to a catch. The catch is usually used to display a message as in the last code. Here is an example:
#include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers: "; try { cout << "First Number: "; cin >> Operand1; cout << "Second Number: "; cin >> Operand2; // Find out if the denominator is 0 if( Operand2 == 0 ) throw "Division by zero not allowed"; // Perform a division and display the result Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n"; } catch(const char* Str) // Catch an exception {

// Display a string message accordingly cout << "\nBad Operator: " << Str; } return 0; }

The catch clause can use any type of variable as long as you configure it accordingly. Instead of a string as we have seen, you can send it an integer, then display an error depending on the integer that was sent.
#include <iostream.h> int main() { double Operand1, Operand2, Result; const char Operator = '/'; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: "; cin >> Operand1; cout << "Second Number: "; cin >> Operand2; // Find out if the denominator is 0 if( Operand2 == 0 ) throw 0; // Perform a division and display the result Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result << "\n\n"; } catch(const int n) // Catch an exception { // Display a string message accordingly cout << "\nBad Operator: Division by " << n << " not allowed\n\n"; } return 0; }

Catching Multiple Exceptions The exceptions as we have seen so far dealt with a single exception in a program. Most of the time, a typical program will throw different types of errors. The C++ language allows you to include different catch blocks. Each catch block can face a specific error. The syntax used is:
try { Code to Try } catch(Arg1)

{ One Exception } catch(Arg2) { Another Exception }

The compiler would proceed in a top-down as follows: 1. Following the normal flow control of the program, the compiler enters the try block. 2. If no exception occurs in the try block, the rest of the try block is executed. If an exception occurs in the try block, the try displays a throw that specifies the type of error that happened. a. The compiler gets out of the try block and examines the first catch b. If the first catch doesnt match the thrown error, the compiler proceeds with the next catch. This continues until the compiler finds a catch that matches the thrown error. c. If one of the catches matches the thrown error, its body executes. If no catch matches the thrown error, you have (or the compiler has) two alternatives. If there is no catch that matches the error (which means that you didnt provide a matching catch), the compiler hands the program flow to the operating system (which calls the terminate() function). Another alternative is to include a catch whose argument is three periods: catch(). The catch() is used if no other catch, provided there was another, matches the thrown error. The catch(), if included as part of a catch clause, must always be the last catch, unless it is the only catch of the clause. Multiple catches are written if or when a try block is expected to throw different types of errors. Imagine a program that requests some numbers from the user and performs some operation on the numbers. Such a program can be written as follows:
#include <iostream.h> int main() { double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break;

case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; default: cout << "Bad Operation"; } cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; cout << "\n\n"; return 0; }

This program works fine as long as the user types a valid sequence of values made of a number followed by a valid arithmetic operator, followed by a number. Anything else, such as an invalid number, an unexpected operator, or a wrong sequence (such as Number Number Operator), would produce an unpredictable outcome. Obviously various bad things could happen when this program is running. To handle the exceptions that this program could produce, you can start with the most likely problem that would occur. Trusting that a user is able to provide the two numbers that are requested, it is possible that she would type an invalid operator. For example, for this program we will perform only the addition (+), the subtraction(-), the multiplication(*), and the division(/). Therefore, we will first validate the operator. This can be done as follows:
#include <iostream> #include <string> using namespace std; int main() { double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; switch(Operator) { case '+': Result = Operand1 + Operand2;

break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; } cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } cout << "\n\n"; return 0; }

When this program runs, if the user provides two valid numbers but a wrong operator, the program asks a throw to send a character (in fact the character that was typed as the operator) that represents the error. Then, when the compiler gets out of the try block, it looks for and finds a catch clause that receives a character value. Therefore, this catch is executed. Imagine that the user wants to perform a division. You need to tell the compiler what to do if the user enters the denominator as 0 (or 0.00). If this happens, the best option, and probably the only one you should consider, is to display a message and get out. To implement this behavior, we will add another catch block that displays a message:
#include <iostream.h> int main() { double Operand1, Operand2, Result; char Operator; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: cin >> Operand1; cout << "Operator: cin >> Operator; "; ";

cout << "Second Number: "; cin >> Operand2; // Make sure the user typed a valid operator if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; // Find out if the denominator is 0 if(Operator == '/') if(Operand2 == 0) throw 0; // Perform an operation based on the user's choice switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; } // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result << "\n\n"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator\n\n"; } catch(const int p) { cout << "\nBad Operation: Division by " << p << " not allowed\n\n"; } return 0; }

When running this program, if the user types a wrong operator, the compiler considers the integer error, gets out f the try block, and looks for a catch that can use a character. The first catch can validate it and gets executed. If the user enters the right values (Number Operator Number), then the compiler finds out if the

operator entered was a forward slash / used to perform a division. If the user wants to perform a division, the compiler finds out if the second operand, the denominator, is 0. If it is, the program presents a throw that sends an integer. Based on this exception, the compiler gets out of the try block and starts looking for a catch block that can use an integer. The first catch cant, it uses a character. Therefore, the compiler looks at the next catch, if any. Our program provides a second catch that takes an integer as an argument. Therefore, this catch gets executed. Not all our problems are solved. Image the user types an invalid number. The first characteristic of an invalid number is one that contains anything else than a digit (a character between 0 and 9). Since our program performs its operations on decimal numbers, we need to allow the number to have a decimal portion. Instead of expecting numeric values from the user, we will request arrays of characters. We will use the isdigit() function to examine each character entered in order to find out whether any one of them is not a digit. Also, we will allow the user to type a period that separates the decimal part of a number. If any of the characters that the user entered is not a digit, we will throw a string error so a catch can deal with it. This means that we will add a catch that is different from the other already existing ones. So far, we were requesting two double-precision numbers from the user. In order to check each number and validate it, instead of decimals, we will ask the user to type two strings (arrays of characters):
#include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; // Request two numbers from the user cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter two numbers\n"; try { cout << "First Number: "; cin >> Number1; cout << "Operator: "; cin >> Operator; cout << "Second Number: "; cin >> Number2; // Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1;// Send the error as a string Operand1 = atof(Number1);

// Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;// Send the error as a string Operand2 = atof(Number2); // Make sure the user typed a valid operator if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; // Find out if the denominator is 0 if(Operator == '/') if(Operand2 == 0) throw 0; // Perform an operation based on the user's choice switch(Operator) { case '+': Result = Operand1 + Operand2; break; case '-': Result = Operand1 - Operand2; break; case '*': Result = Operand1 * Operand2; break; case '/': Result = Operand1 / Operand2; break; } // Display the result of the operation cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result << "\n\n"; } catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed\n\n"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator\n\n"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number\n\n"; }

return 0; }

Nesting Exceptions The calculator simulator we have studied so far performs a division as one of its assignments. We learned that, in order to perform any operation. The compiler must first make sure that the user has entered a valid operator. Provided the operator is one of those we are expecting, we also asked the compiler to check that valid numbers were entered. Even if these two criteria are met, it was possible that the user enter 0 for the denominator. The block that is used to check for a non-zero denominator depends on the exception that validates the operators. In other words, before we check the value of the denominator, we have first made sure that a valid number (a string that contains only digits and a period) was entered for the denominator. For this reason, the exception that could result from a zero denominator depends on the user first entering a valid number for the denominator. C++ allows you to nest exceptions, using the same techniques we applied to nest conditional statements. This means that you can write an exception that depends on, and is subject to, another exception. To nest an exception, write a try block in the body of the parent exception. The nested try block must be followed by its own catch(es). To effectively handle the exception, make sure you include an appropriate throw in the try block. Here is an exception:
#include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++)

if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;//[j]; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; switch(Operator) { case '+': Result = Operand1 + Operand2; cout << "\n" << Operand1 << " + " << Operand2 << " = " << Result; break; case '-': Result = Operand1 - Operand2; cout << "\n" << Operand1 << " - " << Operand2 << " = " << Result; break; case '*': Result = Operand1 * Operand2; cout << "\n" << Operand1 << " * " << Operand2 << " = " << Result; break; case '/': // The following exception is nested in the previous try try { if(Operand2 == 0) throw "Division by 0 not allowed"; Result = Operand1 / Operand2; cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result; } catch(const char * Str) { cout << "\nBad Operation: " << Str; } break; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number";

} cout << "\n\n"; return 0; }

Exceptions and Functions One of the most effective techniques used to deal with code is to isolate assignments. We have learned this when studying functions. For example, the switch statement that was performing the operations in the normal version of our program can be written as follows:
#include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; char Operator; double Calculator(const double N1, const double N2, const char p); cout << "This program allows you to perform a division of two numbers\n"; cout << "To proceed, enter a number, an operator, and a number:\n"; cin >> Operand1 >> Operator >> Operand2; Result = Calculator(Operand1, Operand2, Operator); cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; cout << "\n\n"; return 0; } double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; break; case '-': Value = Oper1 - Oper2; break; case '*': Value = Oper1 * Oper2; break; case '/': Value = Oper1 / Oper2;

break; } return Value; }

You can still use regular functions along with functions that handle exceptions. Here is an example:
#include <iostream> #include <string> using namespace std; double Calculator(const double N1, const double N2, const char p); int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2;//[j]; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; if(Operator == '/') if(Operand2 == 0) throw 0; Result = Calculator(Operand1, Operand2, Operator); cout << "\n" << Operand1 << " " << Operator << " " << Operand2 << " = " << Result; }

catch(const int n) { cout << "\nBad Operation: Division by " << n << " not allowed"; } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; break; case '-': Value = Oper1 - Oper2; break; case '*': Value = Oper1 * Oper2; break; case '/': Value = Oper1 / Oper2; break; } return Value; }

As done in the main() function, any member function of a program can take care of its own exceptions that would occur in its body. Here is an example of an exception handled in a function:
#include <iostream> #include <string> using namespace std; int main() { char Number1[40], Number2[40]; double Operand1, Operand2, Result; char Operator;

void Calculator(const double N1, const double N2, const char p); cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

// Examine each character of the first operand // to find out if the user included a non-digit in the number for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) // Allow the period throw Number1; // Send the error as a character Operand1 = atof(Number1); // Do the same for the second number entered for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) // Allow the period throw Number2; // Send the error as a character Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; Calculator(Operand1, Operand2, Operator); } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2;

cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': // The following try exception is nested in the previous try try { if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; } catch(const char * Str) { cout << "\nBad Operation: " << Str; } break; } }

Isolating assignments and handing them to functions is a complete and important matter in the area of application programming. Consider a program that handles a simple exception such as this one:
#include <iostream> using namespace std; int main() { double Operand1, Operand2, Result; char Operator = '/'; cout << "This program allows you to perform a division of two numbers\n"; try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; if( Operand2 == 0 ) throw "Division by zero not allowed"; Result = Operand1 / Operand2;

cout << "\n" << Operand1 << " / " << Operand2 << " = " << Result; } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; }

One of the ways you can use functions in exception routines is to have a central function that receives variables, sends them to an external function. The external function tests the value of a variable. If an exception occurs, the external function displays or sends a throw. This throw can be picked up by the function that sent the variable. If the throw carries a value such as an integer or a string, the function that originated the try can hand it to a catch or one of its catches to handle the exception. Observe the following example that implements this scenario:
#include <iostream> using namespace std; void Division(const double a, const double b); int main() { double Operand1, Operand2; cout << "This program allows you to perform a division of two numbers\n"; // Start an exception try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; // Pass the new values to a function that will analyze them Division(Operand1, Operand2); } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; } void Division(const double a, const double b) { double Result; // If an exception occurred, if( b == 0 ) // then throw a string to the function caller throw "Division by zero not allowed";

Result = a / b; cout << "\n" << a << " / " << b << " = " << Result; }

In this program, the Division function receives two values that it is asked to perform and division with. The Division function analyzes the second argument that represents the denominator. If this argument is zero, an exception is fund and the Division functions throws a string back to the function that sent the arguments. C++ (as described in the C++ Standards), allows you to specify that a function is an exception carrier. If you write a function that carries an exception, you can type the throw keyword followed by parentheses on the right side of the function. Here is an example:
#include <iostream> using namespace std; void Division(const double a, const double b) throw(); int main() { double Operand1, Operand2; cout << "This program allows you to perform a division of two numbers\n"; // Start an exception try { cout << "To proceed, enter two numbers: "; cin >> Operand1 >> Operand2; // Pass the new values to a function that will analyze them Division(Operand1, Operand2); } catch(const char* Str) { cout << "\nBad Operator: " << Str; } cout << "\n\n"; return 0; } void Division(const double a, const double b) throw() { double Result; // If an exception occurred, if( b == 0 ) // then throw a string to the function caller throw; Result = a / b; cout << "\n" << a << " / " << b << " = " << Result; }

As if it were a function, the throw keyword used like this must have parentheses. If it doesnt take any

argument, the parentheses must be left empty as in the last example. If the function that is called from a try block will throw a specific type of exception, you can specify this in the parentheses of the throw. Here is an example:
#include <iostream> #include <string> using namespace std; void Calculator(const double N1, const double N2, const char p) throw(const char*); int main() { char Number1[40], Number2[40]; double Operand1, Operand2; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

for(int i = 0; i < strlen(Number1); i++) if( (!isdigit(Number1[i])) && (Number1[i] != '.') ) throw Number1; Operand1 = atof(Number1); for(int j = 0; j < strlen(Number2); j++) if( (!isdigit(Number2[j])) && (Number2[j] != '.') ) throw Number2; Operand2 = atof(Number2); if(Operator != '+' && Operator != '-' && Operator != '*' && Operator != '/') throw Operator; try { Calculator(Operand1, Operand2, Operator); } catch(const char * Str) { cout << "\nBad Operation: " << Str; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) {

cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) throw(const char*) { double Value; switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } }

A function can also be called to perform more than one test to eventually throw more than one exception. Such a function can (and should) be programmed to throw different types of exceptions. Here is an eample of such a function:
double Calculator(const double Oper1, const double Oper2, const char Symbol) { double Value; if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol;

switch(Symbol) { case '+': Value = Oper1 + Oper2; cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } return Value; }

As you can see, this function throws two different types of exceptions: a character and a string. When writing such a function that throws, but doesnt handle, different exceptions, you should make sure this function throws different types of exceptions. Here is the reason. When a function throws an exception, it only sometimes specifies the type of exception. It doesnt specify where the exception is going. When the function that called this function receives the thrown type, it must figure out what block must catch the throw. If this function (the function that was called) throws various exceptions of the same type, the calling function would send all of them to the same catch. On the other hand, if the called function throws different types of exceptions, the calling function, when it receives the throws, can send each to the appropriate type that would handle it. When a function throws an exception, we learned that we can use the throw keyword on the right side of the function as if it were a function. We also learned to pass an argument to the throw to specify the type of exception that the called function would deal with. If a function is programmed to throw different types of exceptions, you can specify this in the arguments of the throw that is appended to the function. Here are examples:
#include <iostream> #include <string> using namespace std;

void Calculator(const double N1, const double N2, const char p) throw(const char*, const char); double Validate(const char *N) throw(const char*); int main() { char Number1[40], Number2[40]; double Operand1, Operand2; char Operator; cout << "This program allows you to perform an operation on two numbers\n"; try { cout cout cout cout << << << << "To proceed, enter\n"; "First Number: "; cin >> Number1; "An Operator: "; cin >> Operator; "Second Number: "; cin >> Number2;

Operand1 = Validate(Number1); Operand2 = Validate(Number2); try { Calculator(Operand1, Operand2, Operator); } catch(const char * Str) { cout << "\nBad Operation: " << Str; } } catch(const char n) { cout << "\nOperation Error: " << n << " is not a valid operator"; } catch(const char *BadOperand) { cout << "\nError: " << BadOperand << " is not a valid number"; } cout << "\n\n"; return 0; } void Calculator(const double Oper1, const double Oper2, const char Symbol) throw(const char*, const char) { double Value; if(Symbol != '+' && Symbol != '-' && Symbol != '*' && Symbol != '/') throw Symbol; switch(Symbol) { case '+': Value = Oper1 + Oper2;

cout << "\n" << Oper1 << " + " << Oper2 << " = " << Value; break; case '-': Value = Oper1 - Oper2; cout << "\n" << Oper1 << " - " << Oper2 << " = " << Value; break; case '*': Value = Oper1 * Oper2; cout << "\n" << Oper1 << " * " << Oper2 << " = " << Value; break; case '/': if(Oper2 == 0) throw "Division by 0 not allowed"; Value = Oper1 / Oper2; cout << "\n" << Oper1 << " / " << Oper2 << " = " << Value; break; } } double Validate(const char* N) throw(const char*) { double Valid; for(int i = 0; i < strlen(N); i++) if( (!isdigit(N[i])) && (N[i] != '.') ) throw N; Valid = atof(N); return Valid; }

Você também pode gostar