Language is the only instrument of science . . .
SAMUEL JOHNSON (1709–1784)
In this section we introduce you to the C++ programming language, which is the programming language used in this book.
The first thing that people notice about the C++ language is its unusual name. Is there a C programming language, you might ask? Is there a C– or a C– – language? Are there programming languages named A and B? The answer to most of these questions is no. But the general thrust of the questions is on the mark. There is a B programming language; it was not derived from a language called A, but from a language called BCPL. The C language was derived from the B language, and C++ was derived from the C language. Why are there two pluses in the name C++? As you will see in the next chapter, ++ is an operation in the C and C++ languages, so using ++ produces a nice pun. The languages BCPL and B do not concern us. They are earlier versions of the C programming language. We will start our description of the C++ programming language with a description of the C language.
The C programming language was developed by Dennis Ritchie of AT&T Bell Laboratories in the 1970s. It was first used for writing and maintaining the UNIX operating system. (Up until that time UNIX systems programs were written either in assembly language or in B, a language developed by Ken Thompson, who is the originator of UNIX.) C is a general-purpose language that can be used for writing any sort of program, but its success and popularity are closely tied to the UNIX operating system. If you wanted to maintain your UNIX system, you needed to use C. C and UNIX fit together so well that soon not just systems programs, but almost all commercial programs that ran under UNIX were written in the C language. C became so popular that versions of the language were written for other popular operating systems; its use is not limited to computers that use UNIX. However, despite its popularity, C is not without its shortcomings.
The C language is peculiar because it is a high-level language with many of the features of a low-level language. C is somewhere in between the two extremes of a very high-level language and a low-level language, and therein lies both its strengths and its weaknesses. Like (low-level) assembly language, C language programs can directly manipulate the computer’s memory. On the other hand, C has many features of a high-level language, which makes it easier to read and write than assembly language. This makes C an excellent choice for writing systems programs, but for other programs (and in some sense even for systems programs), C is not as easy to understand as other languages; also, it does not have as many automatic checks as some other high-level languages.
To overcome these and other shortcomings of C, Bjarne Stroustrup of AT&T Bell Laboratories developed C++ in the early 1980s. Stroustrup designed C++ to be a better C. Most of C is a subset of C++, and so most C programs are also C++ programs. (The reverse is not true; many C++ programs are definitely not C programs.) Unlike C, C++ has facilities to do object-oriented programming, which is a very powerful programming technique described earlier in this chapter. The C++ language continues to evolve. Major new features were added in 2011. This version is referred to as C++11. Minor features were added in 2014. At the time of writing this edition, C++17 is under development and will include additional features such as parallel algorithms.
Display 1.8 contains a simple C++ program and the screen display that might be generated when a user runs and interacts with this program. The person who runs a program is called the user. The output when the program is run is shown in the Sample Dialogue. The text typed in by the user is shown in color to distinguish it from the text output by the program. On the actual screen both texts would look alike. The source code for the program is shown in lines 1–22. The line numbers are shown only for reference. You would not type in the line numbers when entering the program. Keywords with a predefined meaning in C++ are shown in color. These keywords are discussed in Chapter 2. The person who writes the program is called the programmer. Do not confuse the roles of the user and the programmer. The user and the programmer might or might not be the same person. For example, if you write and then run a program, you are both the programmer and the user. With professionally produced programs, the programmer (or programmers) and the user are usually different persons.
1 #include <iostream>
2 using namespace std;
3 int main( )
4 {
5 int numberOfPods, peasPerPod, totalPeas;
6 cout << "Press return after entering a number.\n";
7 cout << "Enter the number of pods:\n";
8 cin >> numberOfPods;
9 cout << "Enter the number of peas in a pod:\n";
10 cin >> peasPerPod;
11 totalPeas = numberOfPods * peasPerPod;
12 cout << "If you have ";
13 cout << numberOfPods;
14 cout << " pea pods\n";
15 cout << "and ";
16 cout << peasPerPod;
17 cout << " peas in each pod, then\n";
18 cout << "you have ";
19 cout << totalPeas;
20 cout << " peas in all the pods.\n";
21 return 0;
22 }
Sample Dialogue
Press return after entering a number. Enter the number of pods: 10 Enter the number of peas in a pod: 9 If you have 10 pea pods and 9 peas in each pod, then you have 90 peas in all the pods.
In the next chapter we will explain in detail all the C++ features you need to write programs like the one in Display 1.8, but to give you a feel for how a C++ program works, we will now provide a brief description of how this particular program works. If some of the details are a bit unclear, do not worry. In this section we just want to give you a feel for what a C++ program is.
The beginning and end of our sample program contain some details that need not concern us yet. The program begins with the following lines:
#include <iostream>
using namespace std;
int main()
{
For now we will consider these lines to be a rather complicated way of saying “The program starts here.”
The
program ends with the following two lines:
return 0;
}
For a simple program, these two lines simply mean “The program ends here.”
The lines in between these beginning and ending lines are the heart of the program. We will briefly describe these lines, starting with the following line:
int numberOfPods, peasPerPod, totalPeas;
This line is called a variable declaration. This variable declaration tells the computer that numberOfPods
, peasPerPod
, and totalPeas
will be used as names for three variables. Variables will be explained more precisely in the next chapter, but itis easy to understand how they are used in this program. In this program the variables are used to name numbers. The word that starts this line, int
, is an abbreviation for the word integer and it tells the computer that the numbers named by these variables will be integers. An integer is a whole number, like 1, 2, −1, −7, 0, 205, −103, and so forth.
The remaining lines are all instructions that tell the computer to do something. These instructions are called statements or executable statements. In this program each statement fits on exactly one line. That need not be true, but for very simple programs, statements are usually listed one per line.
Most of the statements begin with either the word cin
or cout
. These statements are input statements and output statements. The word cin
, which is pronounced “see-in,” is used for input. The statements that begin with cin
tell the computer what to do when information is entered from the keyboard. The word cout
, which is pronounced “see-out,” is used for output, that is, for sending information from the program to the terminal screen. The letter c
is there because the language is C++. The arrows, written <<
or >>
, tell you the direction that data is moving. The arrows, <<
and >>
, are called ‘insert’ and ‘extract,’ or ‘put to’ and ‘get from,’ respectively. For example, consider the line:
cout << "Press return after entering a number.\n";
This line may be read, ‘put "Press…number.\n"
to cout
’ or simply ‘output "Press…number.\n"
’. If you think of the word cout
as a name for the screen (the output device), then the arrows tell the computer to send the string in quotes to the screen. As shown in the sample dialogue, this causes the text contained in the quotes to be written to the screen. The \n
at the end of the quoted string tells the computer to start a new line after writing out the text. Similarly, the next line of the program also begins with cout
, and that program line causes the following line of text to be written to the screen:
Enter the number of pods:
The next program line starts with the word cin
, so it is an input statement. Let’s look at that line:
cin >> numberOfPods;
This line may be read, ‘get numberOfPods
from cin
’ or simply ‘input numberOfPods
’.
If you think of the word cin
as standing for the keyboard (the input device), then the arrows say that input should be sent from the keyboard to the variable numberOfPods
. Look again at the sample dialogue. The next line shown has a 10
written in bold. We use bold to indicate something typed in at the keyboard. If you type in the number 10
, then the 10
appears on the screen. If you then press the Return key (which is also sometimes called the Enter key), that makes the 10
available to the program. The statement which begins with cin
tells the computer to send that input value of 10
to the variable numberOfPods
. From that point on, numberOfPods
has the value 10
; when we see numberOfPods
later in the program, we can think of it as standing for the number 10.
Consider the next two program lines:
cout << "Enter the number of peas in a pod:\n";
cin >> peasPerPod;
These lines are similar to the previous two lines. The first sends a message to the screen asking for a number. When you type in a number at the keyboard and press the Return key, that number becomes the value of the variable peasPerPod
. In the sample dialogue, we assume that you type in the number 9
. After you type in 9
and press the Return key, the value of the variable peasPerPod
becomes 9
.
The next nonblank program line, shown below, does all the computation that is done in this simple program:
totalPeas = numberOfPods * peasPerPod;
The asterisk symbol, *
, is used for multiplication in C++. So this statement says to multiply numberOfPods
and peasPerPod
. In this case, 10
is multiplied by 9
to give a result of 90
. The equal sign says that the variable totalPeas
should be made equal to this result of 90
. This is a special use of the equal sign; its meaning here is different than in other mathematical contexts. It gives the variable on the left-hand side a (possibly new) value; in this case it makes 90
the value of totalPeas
.
The rest of the program is basically more of the same sort of output. Consider the next three nonblank lines:
cout << "If you have ";
cout << numberOfPods;
cout << " pea Pods\n";
These are just three more output statements that work basically the same as the previous statements that begin with cout
. The only thing that is new is the second of these three statements, which says to output the variable numberOfPods
. When a variable is output, it is the value of the variable that is output. So this statement causes a 10
to be output. (Remember that in this sample run of the program, the variable numberOfPods
was set to 10
by the user who ran the program.) Thus, the output produced by these three lines is:
If you have 10 pea pods
Notice that the output is all on one line. A new line is not begun until the special instruction \n
is sent as output.
The rest of the program contains nothing new, and if you understand what we have discussed so far, you should be able to understand the rest of the program.
If you think of cin
as a name for the keyboard or input device and think of cout
as a name for the screen or the output device, then it is easy to remember the direction of the arrows >>
and <<
. They point in the direction that data moves. For example, consider the statement:
cin >> numberOfPods;
In the above statement, data moves from the keyboard to the variable numberOfPods
, and so the arrow points from cin
to the variable.
On the other hand, consider the output statement:
cout << numberOfPods;
In this statement the data moves from the variable numberOfPods
to the screen, so the arrow points from the variable numberOfPods
to cout
.
The general form of a simple C++ program is shown in Display 1.9. As far as the compiler is concerned, the line breaks and spacing need not be as shown there and in our examples. The compiler will accept any reasonable pattern of line breaks and indentation. In fact, the compiler will even accept most unreasonable patterns of line breaks and indentation. However, a program should always be laid out so that it is easy to read. Placing the opening brace, {
, on a line by itself and also placing the closing brace, }
, on a line by itself will make these punctuations easy to find. Indenting each statement and placing each statement on a separate line makes it easy to see what the program instructions are. Later on, some of our statements will be too long to fit on one line and then we will use a slight variant of this pattern for indenting and line breaks. You should follow the pattern set by the examples in this book, or follow the pattern specified by your instructor if you are in a class.
1 #include <iostream>
2 using namespace std;
3
4 int main()
5 {
6 Variable_Declarations
7
8 Statement_1
9 Statement_2
10 ...
11 Statement_Last
12
13 return 0;
14 }
In Display 1.8, the variable declarations are on the line that begins with the word int
. As we will see in the next chapter, you need not place all your variable declarations at the beginning of your program, but that is a good default location for them. Unless you have a reason to place them somewhere else, place them at the start of your program as shown in Display 1.9 and in the sample program in Display 1.8. The statements are the instructions that are followed by the computer. In Display 1.8, the statements are the lines that begin with cout
or cin
and the one line that begins with totalPeas
followed by an equal sign. Statements are often called executable statements. We will use the terms statement and executable statement interchangeably. Notice that each of the statements we have seen ends with a semicolon. The semicolon in statements is used in more or less the same way that the period is used in English sentences; it marks the end of a statement.
For now you can view the first few lines as a funny way to say “this is the beginning of the program.” But we can explain them in a bit more detail. The first line
#include <iostream>
is called an include
directive. It tells the compiler where to find information about certain items that are used in your program. In this case iostream
is the name of a library that contains the definitions of the routines that handle input from the keyboard and output to the screen; iostream
is a file that contains some basic information about this library. The linker program that we discussed earlier in this chapter combines the object code for the library iostream
and the object code for the program you write. For the library iostream
this will probably happen automatically on your system. You will eventually use other libraries as well, and when you use them, they will have to be named in directives at the start of your program. For other libraries, you may need to do more than just place an include
directive in your program, but in order to use any library in your program, you will always need to at least place an include
directive for that library in your program. Directives always begin with the symbol #
. Some compilers require that directives have no spaces around the #
, so it is always safest to place the #
at the very start of the line and not include any space between the #
and the word include
.
The following line further explains the include
directive that we just explained:
using namespace std;
This line says that the names defined in iostream
are to be interpreted in the “standard way” (std
is an abbreviation of standard). We will have more to say about this line a bit later in this book.
The third and fourth nonblank lines, shown next, simply say that the main part of the program starts here:
int main()
{
The correct term is main function, rather than main part, but the reason for that subtlety will not concern us until Chapter 4. The braces {
and }
mark the beginning and end of the main part of the program. They need not be on a line by themselves, but that is the way to make them easy to find and we will therefore always place each of them on a line by itself.
The next-to-last line
return 0;
says to “end the program when you get to here.” This line need not be the last thing in the program, but in a very simple program it makes no sense to place it anywhere else. Some compilers will allow you to omit this line and will figure out that the program ends when there are no more statements to execute. However, other compilers will insist that you include this line, so it is best to get in the habit of including it, even if your compiler is happy without it. This line is called a return statement and is considered to be an executable statement because it tells the computer to do something; specifically, it tells the computer to end the program. The number 0
has no intuitive significance to us yet, but must be there; its meaning will become clear as you learn more about C++. Note that even though the return
statement says to end the program, you still must add a closing brace, }
, at the end of the main part of your program.
In the previous section you learned what would happen if you ran the C++ program shown in Display 1.8. But where is that program and how do you make it run?
You write a C++ program using a text editor in the same way that you write any other document—a term paper, a love letter, a shopping list, or whatever. The program is kept in a file just like any other document you prepare using a text editor. There are different text editors, and the details of how to use them will vary from one to another, so we cannot say too much more about your text editor. You should consult the documentation for your editor.
The way that you compile and run a C++ program also depends on the particular system you are using, so we will discuss these points in only a very general way. You need to learn how to give the commands to compile, link, and run a C++ program on your system. These commands can be found in the manuals for your system and by asking people who are already using C++ on your system. When you give the command to compile your program, this will produce a machine-language translation of your C++ program. This translated version is called the object code for your program. The object code must be linked (that is, combined) with the object code for routines (such as input and output routines) that are already written for you. It is likely that this linking will be done automatically, so you do not need to worry about linking. But on some systems, you may be required to make a separate call to the linker. Again, consult your manuals or a local expert. Finally, you give the command to run your program; how you give that command also depends on the system you are using, so check with the manuals or a local expert.
Different compilers and different environments might require a slight variation in some details of how you set up a file with your C++ program. Obtain a copy of the program in Display 1.10. It is available for downloading over the Internet. (See the Preface for details.) Alternatively, very carefully type in the program yourself. Do not type in the line numbers. Compile the program. If you get an error message, check your typing, fix any typing mistakes, and recompile the file. Once the program compiles with no error messages, try running the program.
1 #include <iostream>
2 using namespace std;
3
4 int main( )
5 {
6 cout << "Testing 1, 2, 3\n";
7 return 0;
8 }
9
If you cannot compile and run this program, then see the programming tip entitled “Getting Your Program to Run.” It suggests some things to do to get your C++ programs to run on your particular computer setup.
Sample Dialogue
Testing 1, 2, 3
If you get the program to compile and run normally, you are all set. You do not need to do anything different from the examples shown in the book. If this program does not compile or does not run normally, then read on. In what follows we offer some hints for dealing with your C++ setup. Once you get this simple program to run normally, you will know what small changes to make to your C++ program files in order to get them to run on your system.
If your program seems to run, but you do not see the output line
Testing 1, 2, 3
then, in all likelihood, the program probably did give that output, but it disappeared before you could see it. Try adding the following to the end of your program, just before the line return 0;
these lines should stop your program to allow you to read the output.
char letter;
cout << "Enter a letter to end the program:\n";
cin >> letter;
The part in braces should then read as follows:
cout << "Testing 1, 2, 3\n";
char letter;
cout << "Enter a letter to end the program:\n";
cin >> letter;
return 0;
For now you need not understand these added lines, but they will be clear to you by the end of Chapter 2.
If the program does not compile or run at all, then try changing
#include <iostream>
by adding .h
to the end of iostream
, so it reads as follows:
#include <iostream.h>
If your program requires iostream.h
instead of iostream
, then you have an old C++ compiler and should obtain a more recent compiler.
If your program still does not compile and run normally, try deleting
using namespace std;
If your program still does not compile and run, then check the documentation for your version of C++ to see if any more “directives” are needed for “console” input/output.
If all this fails, consult your instructor if you are in a course. If you are not in a course or you are not using the course computer, check the documentation for your C++ compiler or check with a friend who has a similar computer setup. The necessary change is undoubtedly very small and, once you find out what it is, very easy.
If the following statement were used in a C++ program, what would it cause to be written on the screen?
cout << "C++ is easy to understand.";
What is the meaning of \n
as used in the following statement (which appears in Display 1.8)?
cout << "Enter the number of peas in a pod:\n";
What is the meaning of the following statement (which appears in Display 1.8)?
cin >> peasPerPod;
What is the meaning of the following statement (which appears in Display 1.8)?
totalPeas = numberOfPods * peasPerPod;
What is the meaning of this directive?
#include <iostream>
What, if anything, is wrong with the following #include
directives?
a. #include <iostream >
b. #include < iostream>
c. #include <iostream>