2. First Programs
Standard Output
Our next step should be to write a program that communicates the results of its computations. To do that, we must introduce something called standard output. For now, we will pretend that standard output is a piece of paper. In other words, all the programs we write in this chapter will "communicate" their results on a piece of paper.
When writing a C++ program, we will refer to standard output by a word cout
(pronounced see-out). This word is an abbreviation for "character output", because everything, regardless of its true nature, is sent to standard output in the form of characters. Without further ado, let's look at the same program, rewritten so that it writes out its result:
Since this program uses facilities from the C++ library called input-output streams, in reality, it would need to be preceded by two additional lines:
#include <iostream> using namespace std;
We will explain the purpose of these two additional lines in the next chapter. For the rest of this chapter, let's just pretend that we don't need them.
int main() { cout << 5 + 3.14; }
Besides the word cout
, there is one other novelty in this program, namely the symbols '<<
'.
Those symbols denote something called the insertion operator. It takes the value of the expression on its right and sends it to standard output, denoted by the word cout
on its
left.
With that in mind, let us execute this program. To do that, you will need a pencil and a piece of paper. Write 'STDOUT:' at the top of this paper so that we know what the paper represents.
Execution of C++ programs starts with the first statement in the function main
. In this case, there is only one statement in the program to execute. To carry it out, first we compute the result of the expression 5 + 3.14
, which is the number 8.14. Then, we send that result to standard output. Since we have agreed that standard output will be a piece of paper, the number 8.14 should appear on it:
STDOUT: 8.14
It could be said that the word cout
is used to print out some numbers or text on standard output. The phrases 'to print out', 'to print', 'to write out' and 'to output' have the exact same meaning in this context, but the term 'to print' is the most commonly used, a leftover from a bygone age of teleprinters. All the mentioned terms will be used interchangeably.
Running the Programs Online
You can run the programs given in this chapter by using an online service called C++ shell
Just remember that all programs given in this chapter need to be preceded by two additional lines:
#include <iostream> using namespace std;
Here is an entire test program that you can paste into C++ shell:
#include <iostream> using namespace std; int main() { cout << 5 + 3.14; }