Last modified: Sun, 01 Nov 2009 12:52:21 +0200
Complete: ###################- (95%)
1.1 First C++ Program
1.2 Comments
1.3 Basic Input and Output (I/O)
1.4 Examples
1.5 Exercises
Note that
The C and C++ programming languages are quite different from each other, even though they share some common syntax.
|
1.1 First C++ Program
Pedagogical and traditional programming books begin by writing the words Hello World
to the screen. Here is our first program:
01hello.cpp: Outputs Hello World! to the user's screen.
1:
2:
3:
4:
5:
6:
7:
8:
9:
|
// First C++ program
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!";
return 0;
} |
Hello World!
|
The first column shows the source code line numbers, these do not actually appear in the source code.
The C++ source code for our first program is shown in the second column.
The last column shows the output of the program, that is the result of the program once compiled and executed.
This very simple C++ program is saved in a file called 01hello.cpp.
The program outputs the expression Hello World! to the user's screen.
Note that the name of a C++ program file can have the extension .cpp, .c++, .cxx or .cc.
Some guides to compiling and running C++ programs:
Compiling C++ programs and The Dev-C++ compiler.
If you've installed a C++ compiler and set up the proper development environment, you should be able to compile
this C++ program and make it into an executable file.
A compiler translates the statements of program written in a high level language into a low level language,
the machine code. Each computer language has its own compiler.
Examples are: Fortran, C, C++, Java, Pascal, Basic.
Now, we will look at the code line by line.
- Line 1: // First C++ program
This is a comment line. All lines starting with two slash signs (//) are considered as comments.
That is such lines are ignored by the compiler, and they do not have any effect on the executable.
Comments in programs help the programmer (and users) to understand what the program (or section) does.
This becomes especailly important for large program sources, or sources that are part of a larger project where
more than one programmer is developing or using the code.
- Line 2: #include <iostream>
Lines beginning with a hash (or pound) sign (#) are directives for the preprocessor.
The preprocessor runs before the compiler each time the compiler is invoked.
The preprocessor translates any line that begins with a hash symbol into a special command,
getting your code file ready for the compiler. Here, #include <iostream>
tells the preprocessor to include the iostream standard file
which contains the declarations of the basic standard input-output library in C++.
This specific file (iostream) can be found usually under the folder:
for Linux (GCC): /usr/include/
for Windows (Dev-C++): C:\Dev-Cpp\include\
- Line 3: using namespace std;
A namespace allows to group entities like variables, classes, objects and functions under a name.
All elements belonging to the standard C++ library are declared in what is called a std namespace.
For example, cout is defined under std namespace where you can see the details in the file <iostream>.
This line will be included in most of the source codes included in these notes.
If you omit this line, in order to use cout, you need to write the name of the namespace
(std) followed by scope operator (::) before cout.
In fact, you have to put std:: before using any elements of std namespace. Such as, std::cout << "Hello world!";.
- Line 4:
An empty line does nothing except for help the programmer to view the source code more clearly.
- Line 5: int main()
The actual program starts with a function named main(). Every C++ program has a main() function.
In general, a function is a block of code that performs one or more actions. Usually functions are invoked or
called by other functions, but main() is special. When your program starts, first, main() is called automatically.
In C++, each function has a data type. Here data type of the main() is selected as int (integer).
That is, at the end of execution of the main program, main() will return an integer number.
Functions and returning values are discussed in detail on Section 5.
- Lines 6 and 9:
The body of the main() function is enclosed in braces ({}).
- Line 7: cout << "Hello World!";
This line is a C++ statement which performs the only action that generates a visible effect in our first program.
Each statement must end with a semicolon character (;).
Here's how cout is used: type the word cout, followed by the output insertion (or redirection)
operator (<<). Whatever follows the output insertion operator is output to the screen.
If you want to output a string of characters be sure to enclose them in double quotes (" "), as shown on line 7,
"Hello World!".
- Line 8: return 0;
The return statement causes the main() function (i.e. the program) to finish.
All ANSI-compliant programs declare main() to return an int. This value is "returned" to the operating system
when your program completes.
Some programmers signal an error by returning the value different from 0 (in general 1 or -1).
However, in these notes, main() will in general return 0, i.e. we will not generate error signals.
- Finally note that lines 7 and 8 are indented by two spaces; this is for clarity and you can use any number of spaces you like.
This becomes more important as your program grows in size.
1.2 Comments
C++ supports two types of comments:
- // line comment
The C++ compiler ignores everything after and on the same line of a double-slash.
- /* block comment */
C++ ignores everything between the opening comment mark (/*) and closing comment mark (*/). This block of comments may span more than one line.
This is actually taken from C Programming Language.
Example usages are given below.
// This comment does not increase the size of
// the executable file (binary code), nor does
// it affect the performance speed.
/*
This comment does not increase the size of
the executable file (binary code), nor does
it affect the performance speed.
*/
1.3 Basic Input and Output (I/O)
The standard C++ library includes the header file iostream, where the standard input and
output stream objects are declared. One can see 'streams in C++' how to use:
- cout to output data to the screen and
- cin to input data from the keyboard.
Streams are out of scope of this basic tutorial.
Standard Output
By default, the standard output of a program is the screen, the C++ stream object defined to access it is cout.
For now, you can use cout without fully understanding how it works. To output a value to the screen,
we need to use cout, followed by the insertion operator (<<), which you create by typing the
less-than character (<) twice. Even though this is two characters, C++ treats it as one.
Here are some basic usage examples:
cout << "Hello World!"; // Outputs "Hello World!" on the screen
cout << 1299; // Outputs the number 1299 on the screen
cout << x; // Outputs the content of x on the screen
The insertion operator (<<) may be used more than once in a single statement:
cout << "Hi, " << "this is " << "a simple C++ statement";
Note that, cout does not add a line break. For example:
cout << "Computer Programming ";
cout << "is important for engineers.";
will be output as
Computer Programming is important for engineers.
A line break can be added by inserting a '\n' character or a using a endl manipulator.
cout << "Computer Programming \n";
cout << "is important for engineers.";
or
cout << "Computer Programming " << endl;
cout << "is important for engineers.";
These two produce the following (same) output:
Computer Programming is
important for engineers.
Standard Input
By default, the standard input device is the keyboard. The C++ stream object defined to access it is cin.
Handling the standard input is done by applying the overloaded operator of extraction (>>) on the cin stream.
A value can be input from the keyboard and assigned to a variable x as follows:
and two variables can assigned as follows:
or
The following program summaries the use of cout and cin; two integer values are input and their sum is output.
01add.cpp: Calculates the sum of two values input from the keyboard
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
|
// Calculates the sum of two integers
#include <iostream>
using namespace std;
int main()
{
int a, b, total;
cout << "Enter two integers to be added: ";
cin >> a >> b;
total = a + b;
cout << "The sum is " << total << endl;
return 0;
} |
Enter two integers to be added: 22 33
The sum is 55
|
Three integer variables are declared on line 7 (we will see the details of the variables in the next section).
At line 9 variables a and b are assigned with values that are input from the keyboard,
their sum is assigned to the variable total on line 10, and the contents of total is output on line 11.
1.4 Examples
The following program is another example of basic input and output.
Note the use of std:: (removing the need for the using namespace statement),
and the omission of the return statement (which is optional).
01triangle.cpp: Calculates the area of a triangle with the base and height input from the keyboard
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
|
// Calculates the area of a triangle
// given an input of the triangle base and height.
#include <iostream>
int main()
{
float base, height, area;
std::cout << "Enter the base and height of the triangle: ";
std::cin >> base >> height;
area = 0.5*base*height;
std::cout << "The area of the triangle is " << area << std::endl;
} |
Enter the base and height of the triangle:
3.2 4.0
The area of the triangle is 6.4
|
1.5 Exercises
- What is a compiler?
- What is the difference between the compiler and the preprocessor?
- Why is the function main() special?
- What are the two types of comments, and how do they differ?
- Write the smallest program that can be compiled, linked, and run.
- Write a program that outputs following lines to the screen:
Betty Botter bought a bit of butter
The butter Betty Botter bought was a bit bitter
And made her batter bitter.
- Why does the following program fail?
#include <iostream>
using namespace std;
int main()
{
cout << Is there a bug here?";
return 0;
}
- Explain why we use std:: in the following program. What is the the output of program?
#include <iostream>
int main()
{
std::cout << " ## # # " << std::endl;
std::cout << "# ### ###" << std::endl;
std::cout << " ## # # " << std::endl;
return 0;
}
|