Welcome To Answer your Questions

Home Page About Catalog Contact

Programming Doubts!?

Oh! I can't understand C Programming?

Oh! I am tired of learning C++?

_______________________________

Are you looking for a site to help you in learning, Leading, Guiding and understand C, C++, VC++, Visual Basic, VBA?  Then this is a site suit for you to proceed.

Are you looking for Business oppertunities? Then this is a site for you to help, guid and earn more income.

Are you searching for the answers for any type of religious based or personal problems and etc., this is the place for you to get the solutions.

send your questions to timothyasir@yahoo.com.

will be answered within 24 hours.

 

Get a FREE Laptop! Get a FREE Laptop!

Earn Money

Send a mail to asirtim@yahoo.com to get answers for all your business problems.

Please Help Us to Improve/continue our process by submit your Form here!

Submit your Free Inquiry to Orlando Area, Compare Offers from Vacation Rental Owners & Get a Great Deal!

Blog Flux Directory  Science eBooks AMANGO   Get a Degree to Further Your Career.

Get Free Information on getting a degree from an accredited or stats licensed online university from FreeDegreeInfo.com

""Big Bus Company Sightseeing Tours - Book Online NOW""

Your search for a new car begins here. Get a no obligation quote with Harbor Credit from a local dealer now.

Take surveys. Earn rewards. It's that simple. Join Now

Peace! Love! Joy!

This is your site and for you.

Ask whatever doubts you have.

Book your membership to timothyasir@yahoo.com with a subject line as "Book New Member"

Only authorize member can get Delux Membership

Book your Memebership. We will guid you how to earn more.

Get Free CDs!

Send your request to asirtim@yahoo.com with a subject line as Want a Free CD!

We will send you free CD's only for educational purpose. Dont make it money out of it.

Cd's available for C, C++, VC++, System programming in Windows and Linux.

Mathamatics, Statistics, Operations Research.

Micro Biology

English

Compleate this free registration Submit your Free Inquiry to Orlando Area, Compare Offers from Vacation Rental Owners & Get a Great Deal!  and get Free CD for a Language you want.  Just mail it to asirtim@yahoo.com with a subject line as "FreeCD for <Subject>" 

Example "FreeCD to larn Mathamatics"

RESEARCH HELP FOR YOU!

Are you searching for a place to Guide; how to get analysis for your PhD Doctorate Degree?

We will guide you,  help you for your subject with a mathematical aspect using Correlation, Regression, ANOVA, Factor Analysis, and so on.

Students of B.Sc, M.Sc, and Research Scholars can get membership freely for getting free guiding and analysis at timothyasir@yahoo.com with a subject line as 'Research Member!'

 

 



http://www.utc.edu/~cslab/cpsc350/cs350/Notes_on_C++.ps
62 page book on learning how to write C++ code

http://www.blindprogramming.com/ftp/c/
C++ Tutorials and Learning Downloads

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclang98/HTML/_pluslang_organization.asp
C++ Language Reference, according to Microsoft

http://www.intap.net/~drw/cpp/index.htm
Online C++ Tutorial

http://www.cee.hw.ac.uk/~rjp/Coursewww/
Online C and C++ Courses - The material consists of two related courses, each with an integrated set of notes, examples and exercises. The two courses will cover ANSI C and C++.

http://www.functionx.com/bcb/index.htm
Borland C++ Builder Tutorial

http://www.functionx.com/cpp/index.htm
C++ Tutorial

http://swt-www.informatik.uni-hamburg.de/~strunk/cpp/
C++ Tutorial Textbook

http://www.4p8.com/eric.brasseur/cppcen.html
C++ Tutorial for C Users - This text enunciates and illustrates features and basic principles of C++. It is aimed at experienced C users who wish to learn C++.

http://www.devx.com/free/tips/tipresults.asp?whereby=title&CPP=1
C++ Tips

http://www.devx.com/gethelp/gethelp.asp?Area=C%2FC%2B%2B
Get help with C++ - ask your questions and get answers
http://www.gaddisbooks.com/standard/Downloads/introvc.zip
Introduction to Visual C++ (112 K) - This MS-Word document contains a guide for getting started with Microsoft Visual C++ 6.

http://www.ddj.com/articles/2001/0185/languages/c/visual_cpp_tutorial.htm
Visual C++ Tutorial

http://www.gaddisbooks.com/alternate/Downloads/QuickRef.zip
C++ Quick Reference Sheet - This MS-Word document provides many helpful quick references for the C++ languages. It includes references for data types, operators, if statements, loops, cin, cout, and commonly used library functions.

http://www.gaddisbooks.com/standard/Downloads/introcb.zip
Introduction to C++ Builder (131 K) - This MS-Word document contains a guide for getting started with Borland (Inprise) C++ Builder 4.

http://www.programmersheaven.com/filez/cpp/text/DARKCPP.PDF
The Darker Side of C++ Revisited

http://www.linuxdoc.org/HOWTO/C++Programming-HOWTO.html
C++ Programming How To - This document provides a comprehensive list of C++ URL pointers, links to C++ online textbooks, and programming tips on C++.

http://www.cplusplus.com/
cplusplus.com - The C++ resources network - Information, Documentation, Reference, Sourcecodes and Forums about C++ programming language

http://www.cplusplus.com/doc/
The Cplusplus.com Language Tutorial

http://www.oreilly.com/catalog/cplus/chapter/ch07.html
The Programming Process chapter from Practical C++ Programming

http://www.meetit.com/skilltest/CplusTest.html
Free Object Oriented C++ Skills Test

http://www2.links2go.com/topic/C++_Tutorials
C++ Tutorial links

http://www.troubleshooters.com/codecorn/crashprf.htm
Crashproof C++: The bad-old-days of C are over.

http://www.programmersheaven.com/zone3/index.htm
C/C++ Zone

http://web.archive.org/web/20030208004025/http://www.vb-bookmark.com/CppTutorial.html
Links to C++ Tutorial and Beginner's Guides

http://msint12.tripod.com/
C++ Tutorial is available here

http://www.desy.de/user/projects/C++.html
C++ Tutorial

http://www.cs.brown.edu/courses/cs123/javatoc.html
Java to C++ Transition Tutorial

http://www.cygnus.com/misc/wp/
The ISO/ANSI C++ Draft Standard

http://www.dinkumware.com/htm_cpl/index.html
C++ Library Reference

http://library.thinkquest.org/21963/C__~1/C__~1.HTM
C++ Tutorial

http://www.cs.wustl.edu/~schmidt/C++/index.html
C++ Programming Language Tutorials
This material was developed as part of a series of courses on C++ I taught at the University of California, Irvine and at Washington University, St. Louis. I'm making it available on the WWW for anyone who is interested in teaching or learning about C++. These handouts are stored in postscript 4-up on a page.

http://www.gustavo.net/programming/c__tutorials.shtml
C/C++ Tutorial Links

http://www.infosys.tuwien.ac.at/Research/Component/tutorial/prwmain.htm
Standard Template Library for C++

http://www.cs.uregina.ca/dept/manuals/C++/tutorial.html
http://www8.silversand.net/techdoc/cpp/cpplist.htm
C++ Tutorial (Coronado), downloads here: Cptutt22.zip 112kb and Cptuts22.zip 83K (source code)
http://www.redrival.com/bigt/basicc.htm
C/C++ Tutorials

http://www.teststeststests.com/c++test.htm
C++ Syntax Test

http://linknetwork.tripod.com/cplusplus.html
C/C++ Links

http://www.sasked.gov.sk.ca/~ehs/HeiseIntra/C.html
Free C++ Course

http://www.mysteries-megasite.com/linux/C-tutorial.html
C++ Tutorial Links

http://www.dinkumware.com/refcpp.html
The Dinkum C++ Library Reference

http://users.utu.fi/sisasa/oasis/oasis-cc++.html
C/C++ Links

http://www.cee.hw.ac.uk/~pjbk/pathways/cpp1/cpp1.html
Introduction to C++ Programming I

http://www.skylit.com/pascpp/index.html
Pascal and C++ Side by Side

http://www.skylit.com/style/index.html
The 32 Bits of Style by Gary Litvin (C++)

http://webnz.com/robert/cpp_site.html#Learn
Learning C++ - Links

http://doc.trolltech.com/
Qt Reference Documentation and Tutorials

http://www.cs.umd.edu/users/cml/cstyle/
http://www.cs.umd.edu/users/cml/resources/cstyle/
C and C++ Style Guides - This page offers access to my collection of style guides for code written in C and C++. A few documents offer some discussion about the value and utility of such style guides.

http://members.tripod.com/jcarbrey/cpp_programming_sourcecode/tutorial.htm
C++ Tutorial links

http://www.findtutorials.com/list.asp?category=56
C++ Tutorial Links

http://www.findtutorials.com/list.asp?category=60
Visual C++ Tutorial Links

http://www.academicoop.com/Curriculum/visualc++.asp
Visual C++ Resources and Tutorials

http://www.unixreview.com/development/c_plus.shtml
C++ section of Unix review

http://www.inficad.com/~thurmunit/c/
C/C++ Resources

http://www.csci.csusb.edu/dick/samples/c++.html
Pointers to C++ Documentation and Help

http://www.cs.ucf.edu/courses/cop3530/Stl-tut.doc
C++ STL Tutorial
http://www.cs.ucf.edu/courses/cop3530/Stl-sol.doc
Exercise Solutions
R>
http://www.phys.ualberta.ca/~binliu/cc.htm
C/C++ Tutorial Links

http://examware.com/tutor6.html

Programming in C and C++ A web site designed to help people learn to program C/C++ easily, as well as give them many other useful resources
http://www.cprogramming.com

http://www.phys.ualberta.ca/~binliu/cc.htm
C/C++ Tutorials

http://www.planet-source-code.com/vb/Tutorial/default.asp?lngWId=3
C/C++ Tutorials and Articles

http://www.cplus-zone.com/

http://www.vb-bookmark.com/vbCpp.html

http://cplus.about.com/compute/cplus/mbody.htm

http://www2.andrews.edu/~maier/tutor.html
Tutorials in C/C++

http://www.scriptsearch.com/C_and_Cpp/
http://www.scriptsearch.com/C_and_Cpp/Tips_and_Tutorials/
C and C++ Tips and Tutorials from Scriptsearch.com - Online tutorials, tips, and help on programming in Python.

http://www.thefreecountry.com/developercity/freelib.html
Free C and C++ Libraries

http://freebooks.by.ru/view/ObjectWindowsProgGuide/ewtoc.html
Object Windows Programmers Guide, Volume 3 - free book

http://www.1001tutorials.com/cpp/index.shtml
Many C++ Tutorials linked on this page


Introduction to Computers


Overview
Computer A computer is a machine that receives instructions and produces a result after performing an appropriate assignment. Since it is a machine, it expects good and precise directives in order to do something. The end result depends on various factors ranging from the particular capabilities of the machine, the instructions it received, and the expected result.

As a machine, the computer cannot figure out what you want. The computer doesn't think and therefore doesn't make mistakes.

Computer programming is the art of writing instructions (programs) that ask the computer to do something and give a result. A computer receives instructions in many different forms, four of which are particularly important.

The first instructions are given by the manufacturers of various hardware parts such as the microprocessor, the motherboard, the floppy and the CD-ROM drives, etc. These parts are usually made by different companies, setting different and various goals that their particular part can perform. The instructions given to the microprocessor, for example, tell it how to perform calculations, at what speed, and under which circumstances. The instructions given to the motherboard tell it to behave like a city where people and cars can move from one part of the town to another, back and forth, for various reasons; this allows information to flow from one part of the city, I mean one section of the computer, to another.

Once the instructions given to the hardware parts are known, software engineers use that information to give the second sets of instructions to the computer. These instructions, known as an operating system, are usually written by one company. These second instructions tell the computer how to coordinate its different components so the result will be a combination of different effects. This time, the computer is instructed about where the pieces of information it receives are coming from, what to do with them, then where to send the result. This time also the operating system designers impose a lot of behaviors to the computer as a machine. Again this time, some computer languages are developed so that programmers can write applications as the third set of instructions. It is like developing languages that people in a city can use to talk to each other. Consider that from now on (once the OS is developed), people get into the habit of doing things according to their particular culture or taste, speaking different languages that their neighbor doesn't understand... Luckily, the computer, I should say the OS, understands all these languages (I can't guaranty that). Some of the operating systems on the market are: Microsoft Windows 3.X, Corel Linux, IBM OS\2, Microsoft Windows 9X, Apple OS 10, Red Hat Linux, Microsoft Windows Millennium, BeOS, Caldera Linux, Microsoft Windows 2000 etc. A particular OS (for example Microsoft Windows 98) depending on a particular processor (for example Intel Pentium) is sometimes referred to as a platform. Some of the computer languages running on Microsoft Windows operating systems are C++, Pascal, Basic, and their variants.


The actual third set of instructions are given to the computer by you, the programmer, using one or more of the languages that the operating system you are planning to use can understand. Your job is going to consist of writing applications. As a programmer, you write statements such as telling the computer, actually the operating system, that "If the user clicks this, do the following, but if he clicks that, do something else. If the user right clicks, display this; if he double-clicks that, do that." To write these instructions, called programs, you first learn to "speak" one of the languages of the OS. Then, you become more creative... Some of the application programs in the market are Microsoft Word, Lotus ScreenCam, Adobe Acrobat, Jasc Paint Shop Pro, etc.



The last instructions are given by whoever uses your program, or your application. For example, if you had programmed Microsoft Word, you would have told the computer that "If a user clicks the New button on the Standard toolbar, I want you to display a new empty document. But if the user clicks File -> New..., I want you to 'call' the New dialog and provide more options to create a new document. If the same user right-clicks on any button on any of the toolbars, I want you to show, from a popup menu, all the toolbars available so she can choose which one she wants. But if she right-clicks on the main document, here is another menu I want you to display."

At this time, you have probably realized that the users of your programs depend on your techniques as a developer to provide an easy to use application (that's what recruiters and employers call experience and creativity). You depend on the computer language that you are actually using (every computer language has its ups and downs). Your computer language depends on the operating system it is running on (different

operating systems have different strengths and weaknesses). The operating system depends on the microprocessor or the machine it is running in (the biggest difference between two microprocessors is the speeds at which each processes information).

Your interest here is on the computer languages, since you are going to write programs. There are various computer languages, for different reasons, capable of doing different things. Fortunately, the computer can distinguish between different languages and perform accordingly. These instructions are given by the programmer who is using compilers, interpreters, etc, to write programs. Examples of those languages are Basic, C++, Pascal, etc.

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

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
#include



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 semi-colon. 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
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
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++ Standard’s 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 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 , 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.


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
#include

int main(int argc, char *argv[])
{
cout << "C++ is Fun!!!";
getchar();
return 0;
}


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

16. After the program has been compiled, click Execute.
17. 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 #include
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...

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


#include

int main()
{
cout << “C++ is fun!!!\n”;
return 0;
}


7. Save your file. If you are using gedit like me, on the main menu, click File -> Save As...
8. 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.
9. On the left list, double-click your user name (for me that would be root/) to open you personal directory
10. On the left list, double-click the Exercise1/ directory we created.
11. In the Selection: text box, type the name of the file as Exo.cpp and click OK
12. 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]$
13. 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]$
14. To compile the program, we will use the free g++ compiler. Therefore, type:
g++ Exo.cpp
15. For example, on mine, I type [jezoo@localhost Exercise1]$ g++ Exo.cpp
16. You may receive one warning. For now, don't worry.
17. To execute the program, type ./a.out and press Enter
18. 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

19. 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
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. Start Microsoft Visual C++.
2. On the main menu of Microsoft Visual C++ or Microsoft Visual Studio, click File -> New...
3. Click the Projects property sheet.
4. Click Win32 Console Application.
5. 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
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
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
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
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
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


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 user’s machine, some of that is from the computer (the operating system and other applications that are running on the same computer), and some will have been created by you as part of your application. When interacting with the computer, the user will enter information mainly using the keyboard and/or the mouse. Regardless of what information the user is using, the things used or needed by your program are stored or will be stored in the computer.
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. This is a hard drive. It keeps its information full time, even 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 auto bad_cast bad_typeid bool
break case catch char class
const const_cast continue default delete
do double dynamic_cast else enum
except explicit extern false finally
float for friend goto if
inline int long mutable namespace
new operator private protected public
register reinterpret_cast return short signed
sizeof static static_cast unsigned struct
switch template this throw true
try type_info typedef typeid typename
union unsigned using virtual void
volatile while

Most compilers also have their own list of reserved words. Because this depends on the compiler, we cannot review all of them. Also, some words are not official keywords but if you use them to name your variables, you may encounter problems. Based on this, avoid using these additional words:
C++ Reserved Words
cout interrupt register string wchar_t

Avoid starting the name of a variable with two underscores such as __finally or __stdcall. Sometimes (most of the time), the compiler would think that you are trying to use one of the words reserved for the compiler.

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:
Representing a Varaible

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.
Representing a Bit

Since this box can have only one of two states, consider that you can use it to represent anything that could assume one out of two states. Examples include: True-False; Parent-Child; On-Off; Discount-NoDiscount; Male-Female; Yes-No, etc.

This technique of representing values is called The Binary system. In the computer, it uses values 0 and/or 1, which themselves are called digits. The entity used to represent such a value is called a binary digit; in its abbreviated form, it is called a bit (for binary digit). The bit (binary digit) is the most fundamental representation of the computer's counting system. Although this is valid for the computer, the Intel microprocessors cannot validate a variable at this level; but eventually, you will be able to manipulate data at the bit level.

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

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

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
Nibble Representation

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:
Representation a Hexadecimal Nibble

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

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

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

As you can see, the binary system is very difficult to read when a value combines various bit representations. To make your life a little easier, the computer recognizes the hexadecimal representation of bits. Following the box combinations above, we can represent each 4-bit of the sixteen combinations using the decimal, hexadecimal, and binary systems as follows:
Decimal Hexadecimal Binary
0 0 0000
1 1 0001
2 2 0010
3 3 0011
4 4 0100
5 5 0101
6 6 0110
7 7 0111
8 8 1000
9 9 1001
10 A 1010
11 B 1011
12 C 1100
13 D 1101
14 E 1110
15 F 1111

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 Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 15 0xf 1111

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



A Byte


Representing a Byte

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.

Byte Orders

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 Hexadecimal Binary
Minimum 0 0x0 0000
Maximum 255 0xff 1111 1111

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

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

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

int main()
{
signed char category = 'D';

cout << "Category: " << category;
cout << endl;

return 0;
}

You can also declare a positive character as unsigned char. Here is an example:


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

int main()
{
char Satisfaction, answer;
signed char ageCategory, size;

cout << "From A to Z, enter a character as your level of satisfaction: ";
cin >> satisfaction;
cout << "Age category(t=teen/a=Adult/s=Senior): ";
cin >> ageCategory;
cout << "Are you drunk(y=Yes/n=No)? ";
cin >> answer;
cout << "Enter your size(s=Small/m=Medium/l=Large): ";
cin >> size;

cout << "\nSatisfaction: " << Satisfaction;
cout << "\nAge category: " << AgeCategory;
cout << "\nYour answer: " << Answer;
cout << "\nYour size: " << Size;

return 0;
}

To keep the integer value of a char positive, you can declare it as an unsigned char. Its value would then range from 0 to 255.


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
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 Sequence Name ASCII value Description
\a Bell (alert) 007 Makes a sound from the computer
\b Backspace 008 Takes the cursor back
\t Horizontal Tab 009 Takes the cursor to the next tab stop
\n New line 010 Takes the cursor to the beginning of the next line
\v Vertical Tab 011 Performs a vertical tab
\f Form feed 012
\r Carriage return 013 Causes a carriage return
\" Double Quote 034 Displays a quotation mark (")
\' Apostrophe 039 Displays an apostrophe (')
\? Question mark 063 Displays a question mark
\\ Backslash 092 Displays a backslash (\)
\0 Null 000 Displays a null character




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:
Representing a word

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

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

int main()
{
unsigned short shirts;
unsigned short pants;
unsigned short dresses;
unsigned short ties;

cout << " -=- Georgetown Cleaning Services -=-\n";
cout << "Enter number of shirts: ";
cin >> shirts;
cout << "Enter number of pants: ";
cin >> pants;
cout << "Enter number of dresses: ";
cin >> dresses;
cout << "Enter number of ties: ";
cin >> ties;

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

return 0;
}

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


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

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

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 219 218 217 216
8,388,608 4,194,304 2,097,152 1,048,576 524,288 262,144 131,072 65,536
215 214 213 212 211 210 29 28
32,768 16,384 8,192 4,096 2,048 1,024 512 256
27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 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
using namespace std;

int main()
{
int coordX, coordY, coordZ;

cout << "Enter the coordinates of point A\n";
cout << "Horizontal X = ";
cin >> coordX;
cout << "Vertical Y = ";
cin >> coordY;
cout << "Depth Z = ";
cin >> coordZ;

cout << "\nOn a cartesian system, point A is located at";
cout << "\n\tX = " << coordX;
cout << "\n\tY = " << coordY;
cout << "\n\tZ = " << coordZ;

return 0;
}

When executed, the program would produce:

Enter the coordinates of point AHorizontal X = -12Vertical Y = 8Depth Z = 6On a cartesian system, point A is located at X = -12 Y = 8 Z = 6Press any key to continue...

The signed is used to designate an integer variable whose value could be negative or positive. You can declare such a variable using one of the following:

signed distanceRange;
signed int velocity;

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

signed int pagePosition;

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

unsigned int pageCount;

An unsigned integer can also be declared simply with the unsigned keyword. Here is an example:

#include
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 LearningPractical Learning: Using Integer Variables

1. To use integer variables, change the source file as follows:


#include
using namespace std;

int main()
{
unsigned short shirts;
unsigned short pants;
unsigned short dresses;
unsigned short 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 << "\n====================================";
cout << "\n-=- Georgetown Cleaning Services -=-";
cout << "\n====================================";
cout << "\nCustomer Order";
cout << "\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 the date this order was placed
Order Day: 18
Order Month: 06
Order Year: 2000
Enter number of shirts: 2
Enter number of pants: 0
Enter number of dresses: 3
Enter 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
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
using namespace std;

int main()
{
float side, perimeter, area;

cout << "Enter the side of the square: ";
cin >> side;

perimeter = side * 4;

area = side * side;

cout << "Characteristics of the square:";
cout << "\nSide: " << side;
cout << "\nPerimeter: " << perimeter;
cout << "\nArea: " << area;

return 0;
}

Floating-Point Numbers With Double-Precision

When a variable is larger than the float can handle and requires more precision, you should use the double identifier. The double-precision identifier is an 8 Byte decimal or fractional number ranging from 1.7 x 10-308 to 1.7 x 10308.

Here is an example:

#include
using namespace std;

int main()
{
float side, perimeter, area;

cout << "Enter the side of the square: ";
cin >> side;

perimeter = side * 4;

area = side * side;

cout << "Characteristics of the square:";
cout << "\nSide: " << side;
cout << "\nPerimeter: " << perimeter;
cout << "\nArea: " << area;

return 0;
}

For an even larger variable, use the 10 Byte real data type identified as a long double data type that ranges from 3.4 x 10-4932 to 1.1 x 104932.

Here is an example that uses the long double data type:

#include
using namespace std;

int main()
{
long double radius = 15.625, Radius = 18.125;
long double area, Area, TotalArea;

Area = Radius * Radius * 3.14159;
area = radius * radius * 3.14159;
TotalArea = Area - area;

cout << "Properties of the plate";
cout << "\nExternal Radius: " << Radius;
cout << "\nInternal Radius: " << radius;
cout << "\nArea: " << TotalArea;

return 0;
}



Practical LearningPractical Learning: Using Floating-Point Numbers

1. To use decimal variables, change the source file as follows:


#include
using namespace std;

int main()
{
unsigned short shirts;
unsigned short pants;
unsigned short dresses;
unsigned short ties;

double priceShirts = 1.25;
double pricePants = 2.75;
double priceDresses = 3.25;
double priceTies = 1.65;

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 << "\n====================================";
cout << "\n-=- Georgetown Cleaning Services -=-";
cout << "\n====================================";
cout << "\nCustomer Order";
cout << "\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
using namespace std;

int main()
{
char University[] = "University of the District of Columbia";
char Faculty[]("Computer sciences");

cout << "Welcome to the Student Orientation Program.\n";
cout << "For your studies, we have selected:\n";
cout << "Institution: " << University << "\n";
cout << "Faculty: " << Faculty << "\n";

return 0;
}

To request an array from the user, simply type the name of the array variable on the right side of the cin >> operator. Here is an example:

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

int main()
{
char FirstName [20], LastName [20];
char Address [40];
char JobPerformed [80];

cout << "Welcome to College Park Auto-Parts\n";
cout << "Enter the following information about the customer's.\n";
cout << "First Name: ";
cin >> ws;
cin.getline(FirstName, 20);
cout << "Last Name: ";
cin >> ws;
cin.getline(LastName, 20);
cout << "Address: ";
cin >> ws;
cin.getline(Address, 40);
cout << "Describe the job performed on the customer's car in 100 words or less:\n";
cin >> ws;
cin.getline(JobPerformed, 80);

cout << "\nCPAP Invoice # 1202";
cout << "\nCustomer Name: " << FirstName << " " << LastName;
cout << "\nAddress: " << Address;
cout << "\nJob Performed: " << JobPerformed;
cout << "\n\n";

return 0;
}



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

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

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

double priceShirts = 1.25;
double pricePants = 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: " << 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:


Enter the date this order was placed
Order Day: 02
Order Month: 11
Order Year: 2001
Enter number of shirts: 6
Enter number of pants: 4
Enter number of dresses: 2
Enter 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 one-word variable. Here is an example program that requests a first and last names:

#include
#include
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
#include
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
#include
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 getline() function as follows:

#include
#include
using namespace std;

int main()
{
string FirstName, LastName;
string Address;
string JobPerformed;

cout << "Welcome to College Park Auto-Parts\n";
cout << "Enter the following information about the customer's.\n";
cout << "First Name: ";
cin >> FirstName;
cout << "Last Name: ";
cin >> LastName;
cout << "Address: ";
getline(cin, Address);
cout << "Describe the job performed on the customer's car:\n";
getline(cin, JobPerformed);

cout << "\n\nCPAP Invoice # 1202";
cout << "\nCustomer Name: " << FirstName << " " << LastName;
cout << "\nAddress: " << Address;
cout << "\nJob Performed: " << JobPerformed << "\n\n";

return 0;
}

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

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

return 0;
}

You can also assign the resulting value to a variable before using it:

#include
using namespace std;

int main()
{
int number = static_cast(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
using namespace std;

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

number = static_cast(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
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
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
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
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
using namespace std;

double number;

int main()
{

return 0;
}

After declaring the variable, you can initialize it immediately:

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

C++ Note
Some languages such as Pascal or Visual Basic support global variables. Some other languages such as Java and C# don't support them



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
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
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: " << InterestAndDiscount::rate*100 << "%";
cout << "\nTime: " << InterestAndDiscount::periods << " years" << endl;

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
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: " << InterestAndDiscount::rate << "%";
cout << "\nPeriods: " << InterestAndDiscount::periods << " years" << endl;

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
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
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: " << rate << "%";
cout << "\nPeriods: " << 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
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
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: $" << principal
<< "\nRate: " << rate << "%"
<< "\nDiscount: " << discount
<< "\nPeriods: " << 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
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: $" << principal
<< "\nRate: " << rate << "%"
<< "\nDiscount: " << discount
<< "\nPeriods: " << 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
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
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
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
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 iomanip list ostream streambuf
bitset ios locale queue string
complex iosfwd map set typeinfo
deque iostream memory sstream utility
exception istream new stack valarray
fstream iterator numeric stdexcept vector
functional limits

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

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

You can type:

#include
using namespace std;

Because this second technique is conform with the C++ Standard, we will use it whenever we need one of its libraries.

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
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
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
#include
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 student’s first name would be a word representing a student’s 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 member’s applications at a sports club. You can define a function that would request the first and last names; other functions that need a member’s 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
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
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
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 student’s 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 function’s 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 student’s first name could be declared as:

string FirstName();

Here are examples of declaring functions; some take arguments, some don’t:

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 function’s 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
#include
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 << endl << FullName << "'s Weekly Hours\n";
cout << "Monday: "; cin >> Mon;
cout << "Tuesday: "; cin >> Tue;
cout << "Wednesday: "; cin >> Wed;
cout << "Thursday: "; cin >> Thu;
cout << "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 item’s purchase price based on the item’s 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 item’s 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
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 argument’s value and gives it to the calling function. Although the calling function receives the argument’s 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
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 << "\nIn the main() function,";
cout << "\n\tWeekly Hours = " << hours;
cout << "\n\tSalary = $" << rate;
cout << "\n\tWeekly Salary: $" << hours * rate;
cout << "\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 << "\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 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 << "\n\nIn the Earnings() function,";
cout << "\n\tWeekly Hours = " << thisWeek;
cout << "\n\tSalary = " << salary;
cout << "\n\tWeekly 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
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
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
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
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.


The Moment Of Inertia

Here is an example that calculates the moment of inertia with regard to the X axis:

#include
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:
The Moment of Inertia for a 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
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
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
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
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

Click the link for learning more













Google